1

我有一个抽象模型,从中继承了我的几个主要模型。在这种情况下,主要困难是我需要参考相同的模型,比如 a ForeignKeyto self。我已经读过抽象模型ForeignKey中不可能并且可以提供帮助,但是我不能真正使它起作用。GenericForeignKey

据我了解,结构应该如下所示:

class BaseModel(models.Model):
    versions = GenericRelation('self')
    date_created = models.DateTimeField(default=datetime.datetime.now)
    is_deleted = models.BooleanField(default=False)

    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

class FirstModel(BaseModel):
    some_fields...

class AnotherModel(BaseModel):
    another_fields...

但是用这种方法我得到一个错误:

>>> item1 = FirstModel.objects.get(id=1)
>>> item2 = FirstModel.objects.get(id=2)
>>> item2.content_object = item1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 245, in __set__
    ct = self.get_content_type(obj=value)
  File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 163, in get_content_type
    return ContentType.objects.db_manager(obj._state.db).get_for_model(
AttributeError: 'ReverseGenericRelatedObjectsDescriptor' object has no attribute '_state'

我试图达到的目标是绝对不可能的,唯一的解决方案是在现有模型中显式创建所需的字段吗?

4

1 回答 1

2

我试图ForeignKey在抽象模型上复制您的问题,但它似乎适用于 Django 版本 1.11.1:

class BaseModel(models.Model):
    other = models.ForeignKey('self', null=True, blank=True)

    class Meta:
        abstract = True

class FirstModel(BaseModel):
    pass

class AnotherModel(BaseModel):
    pass

使用模型:

>>> fm1 = FirstModel.objects.create()
>>> fm2 = FirstModel.objects.create()
>>>
>>> fm1.other = fm2
>>> fm1.save()

以下分配给 other 会导致错误:

>>> am = AnotherModel.objects.create()
>>> am.other = fm1
ValueError: Cannot assign "<FirstModel: FirstModel object>": "AnotherModel.other" must be a "AnotherModel" instance.
于 2018-01-02T16:02:00.140 回答