与Django中抽象模型相关的ForeignKey字段

与Django中抽象模型相关的ForeignKey字段,第1张

与Django中抽象模型相关的ForeignKey字段

在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)> ]

考虑到这些查询的性能会稍差一些。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5648532.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存