我有一个称为参数的抽象对象。参数可以是几种不同的类型。例如-数值参数,常量参数,多值参数等。每个参数可以与许多不同类型的参数相关,反之亦然。
在复习Django的有关模型继承的文档之后,我决定需要一个简单的抽象基类。稍后可以在文档中找到基类的多对多关系示例。
class ParameterBase(models.Model):
id = models.AutoField(primary_key=True)
description = models.CharField(max_length=200)
sort_order = models.DecimalField(null=False, max_digits=6, decimal_places=4)
m2m = models.ManyToManyField('self',related_name='dependent_on')
class Meta:
abstract = True
class ParameterConstant(ParameterBase):
value = models.DecimalField(null=False, blank=False, max_digits=20 , decimal_places=4)
class ParameterNumeric(ParameterBase):
minimum = models.DecimalField(null=True, blank=True, max_digits=20 , decimal_places=4)
maximum = models.DecimalField(null=True, blank=True, max_digits=20 , decimal_places=4)
因此,同步后,我可以看到django创建了4个表-
CREATE TABLE "calc_parameterconstant_m2m" (
"id" serial NOT NULL PRIMARY KEY,
"from_parameterconstant_id" integer NOT NULL,
"to_parameterconstant_id" integer NOT NULL,
UNIQUE ("from_parameterconstant_id", "to_parameterconstant_id")
)
;
CREATE TABLE "calc_parameterconstant" (
"id" serial NOT NULL PRIMARY KEY,
"description" varchar(200) NOT NULL,
"sort_order" numeric(6, 4) NOT NULL,
"value" numeric(20, 4) NOT NULL
)
;
ALTER TABLE "calc_parameterconstant_m2m" ADD CONSTRAINT "from_parameterconstant_id_refs_id_f893bb67" FOREIGN KEY ("from_parameterconstant_id") REFERENCES "calc_parameterconstant" ("id") DEFERRABLE INITIALLY DEFERRED;
ALTER TABLE "calc_parameterconstant_m2m" ADD CONSTRAINT "to_parameterconstant_id_refs_id_f893bb67" FOREIGN KEY ("to_parameterconstant_id") REFERENCES "calc_parameterconstant" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE TABLE "calc_parameternumeric_m2m" (
"id" serial NOT NULL PRIMARY KEY,
"from_parameternumeric_id" integer NOT NULL,
"to_parameternumeric_id" integer NOT NULL,
UNIQUE ("from_parameternumeric_id", "to_parameternumeric_id")
)
;
CREATE TABLE "calc_parameternumeric" (
"id" serial NOT NULL PRIMARY KEY,
"description" varchar(200) NOT NULL,
"sort_order" numeric(6, 4) NOT NULL,
"minimum" numeric(20, 4),
"maximum" numeric(20, 4)
)
现在,这显然不是我的意图-我希望也能够将每种类型的参数连接到其他类型的参数。有什么方法可以使用Django ORM和模型继承来实现此目标?
如果基本参数模型本身就是一个具有自身与多对多关系的表,并且子表与一个解除绑定的一对一关系相连,那么在数据库方面,这可能是一个很好的解决方案。
我认为多表继承将解决您的问题。要使用它,只需abstract = True
从ParameterBase.Meta
子类中删除(或完全删除该子类)。
使用多表继承时,要访问特定子类的属性,Django必须知道您正在处理该子类。
例如,这将失败:
p = ParameterBase.objects.get(...) # get a ParameterBase that is a ParameterConstant
print p.value
相反,您将必须执行以下操作:
p = ParameterConstant.objects.get(...)
print p.value
或这个:
p = ParameterBase.objects.get(...) # get a ParameterBase that is a ParameterConstant
print p.paramaterconstant.value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句