Django在抽象模型

时间:2018-01-02 15:14:34

标签: python django django-generic-relations

我有一个抽象模型,我的几个主要模型都是从中继承的。在这种情况下的主要困难是我需要参考相同的模型,例如ForeignKeyself。我已经读过抽象模型中无法ForeignKeyGenericForeignKey可以提供帮助,但我无法真正发挥作用。

据我所知,结构应如下所示:

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'

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

1 个答案:

答案 0 :(得分: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()

以下分配给其他人导致错误:

>>> am = AnotherModel.objects.create()
>>> am.other = fm1
ValueError: Cannot assign "<FirstModel: FirstModel object>": "AnotherModel.other" must be a "AnotherModel" instance.