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

Saf*_*ari 12 python django foreign-keys abstract

我有这个型号:

class BaseModel(models.Model):
    ....

    class Meta:
        abstract = True


class ModelA(BaseModel):
    ....

class ModelB(BaseModel):
    ....


class MyExtModel(models.Model)
    myfield = models.ForeignKey(BaseModel)
Run Code Online (Sandbox Code Playgroud)

但这不正确,因为我BaseModel喜欢Abstract.事实上,当我尝试makemigration命令时,我有一个错误.

错误是:

ERRORS:
myapp.MyExtModel.myfield: (fields.E300) Field defines a relation with model 'BaseModel', which is either not installed, or is abstract.
Run Code Online (Sandbox Code Playgroud)

有没有办法使用抽象基础模型?

我也试过用:

myfield = models.ForeignKey(BaseModel, related_name="%(app_label)s_%(class)s_related")
Run Code Online (Sandbox Code Playgroud)

Seb*_*zny 13

在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"> ]
Run Code Online (Sandbox Code Playgroud)

要使用django polymorphic,您只需要将具有Polymorphic Model的模型声明为基类:

from django.db import models
from polymorphic.models import PolymorphicModel

class 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)
Run Code Online (Sandbox Code Playgroud)

外键也将返回子类实例,这是我需要的假设:

# The model holding the relation may be any kind of model, polymorphic or not
class 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)> ]
Run Code Online (Sandbox Code Playgroud)

考虑到这些查询的性能稍差.

  • 我不知道 PolymorphicModel ...也许这可以帮助我。我不明白一方面:PolymorphicModel 是基于 GenericRelation?什么时候需要使用GenericRelation(内容类型)而不是PolymorphicModel?可能这个问题脱离了我原来问题的背景...... (2认同)

Alv*_*oAV 6

当我遇到这样的情况时,必须选择不同模型的ForeignKeys,GenericForeignKey您可以在此处查看官方文档:Django ContentTypes:Generic Relations

该文档很好地解释了如何使用它:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __str__(self):              # __unicode__ on Python 2
        return self.tag
Run Code Online (Sandbox Code Playgroud)
  • 字段content_type存储通用外键指向的模型

  • 字段object_id存储外键的ID,

  • 字段content_object可帮助您基于其他2个字段直接访问相关对象

这不是最好的解决方案,但可以节省一些项目

使用示例:

from django.contrib.auth.models import User
guido = User.objects.get(username='Guido')
t = TaggedItem(content_object=guido, tag='bdfl')
t.save()
t.content_object
<User: Guido>
Run Code Online (Sandbox Code Playgroud)


Wto*_*wer 5

除了GenericForeignKey我不太熟悉的很好的答案之外,有时(只是有时,只要可能),通过使用与“基本”模型的一对一关系来简化模型是值得的。

之后使外键管理变得更容易。如果我没记错的话,抽象类上的外键是不可能的。