在Django中无法将外键安装到抽象模型。但是,您可以将外键安装到非抽象基类。唯一的限制是反向外键关系将返回基类实例。您可以使用django-
polymorphic来规避此限制。
Django Polymorphic允许您查询基类对象,但可以检索子类实例:
>>> Project.objects.create(topic="Department Party")>>> ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner")>>> ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter")>>> Project.objects.all()[ <Project: id 1, topic "Department Party">, <ArtProject: id 2, topic "Painting with Tim", artist "T. Turner">, <ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ]
要使用django多态,只需要声明以Polymorphic Model为基类的模型即可:
from django.db import modelsfrom polymorphic.models import PolymorphicModelclass ModelA(PolymorphicModel): field1 = models.CharField(max_length=10)class ModelB(ModelA): field2 = models.CharField(max_length=10)class ModelC(ModelB): field3 = models.CharField(max_length=10)
外键还将返回子类实例,这是您需要的:
# The model holding the relation may be any kind of model, polymorphic or notclass RelatingModel(models.Model): many2many = models.ManyToManyField('ModelA') # ManyToMany relation to a polymorphic model>>> o=RelatingModel.objects.create()>>> o.many2many.add(ModelA.objects.get(id=1))>>> o.many2many.add(ModelB.objects.get(id=2))>>> o.many2many.add(ModelC.objects.get(id=3))>>> o.many2many.all()[ <ModelA: id 1, field1 (CharField)>, <ModelB: id 2, field1 (CharField), field2 (CharField)>, <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]
考虑到这些查询的性能会稍差一些。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)