Django中固有的python抽象基类

时间:2018-07-06 08:31:27

标签: python django design-patterns

我想在python中创建一个通用模块,该模块使用Django模型中的数据,并使用键入来记录该接口。该模块应独立于Django模型。应该如何以pythonic的方式完成?

我正在考虑使用ABC类,那么独立的python文件应该类似于(shape.py):

from abc import ABC


class Shape(ABC):
    @property
    @abstractmethod
    def height(self) -> float:
         pass

    @property
    @abstractmethod
    def area(self) -> float:
         pass


class VolumeCalculation:
    def __init__(self, shape: Shape) -> None:
        self.shape = shape

    def volume(self) -> float
        return self.shape.area*self.shape.height

虽然Django模型是在另一个文件中定义的:

from django.db import models
from shape import Shape


class Box(models.Model, Shape):
    height= models.FloatField('height')
    area = models.FloatField('area')

执行此操作时,出现以下错误:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

或者,我可以删除基类并使用Shape中所需的参数构造VolumeCalculation。但是由于实际对象包含许多参数,因此列表变得很长。

1 个答案:

答案 0 :(得分:3)

您不必从Shape派生Shape使其成为from django.db import models from shape import Shape class Box(models.Model): height= models.FloatField('height') area = models.FloatField('area') Shape.register(Box) ,只需Code on Ideone

protected void btnSelect_Click(object sender, EventArgs e)
{
    try /* Select After Validations*/
    {
        using (NpgsqlConnection connection = new NpgsqlConnection())
        {
            connection.ConnectionString = ConfigurationManager.ConnectionStrings["SHOT"].ToString();
            connection.Open();
            NpgsqlCommand cmd = new NpgsqlCommand();
            cmd.Connection = connection;
            cmd.CommandText = "Select * from shot_assessment";
            cmd.CommandType = CommandType.Text;
            NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            cmd.Dispose();
            connection.Close();

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    catch (Exception ex) { }
}