多个模型上的Django GenericForeignKey字段

时间:2016-08-06 20:54:36

标签: python django

有没有办法让GenericForeignKey包含两个与ForeignKey连接的模型的字段?

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

# Create your models here.

class Main(models.Model):
    text = models.TextField()
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)

class Child(models.Model):
    object_id = models.PositiveIntegerField()
    main = models.ForeignKey(Main)
    content_object = GenericForeignKey('main__content_type', 'object_id')

1 个答案:

答案 0 :(得分:1)

我必须为它编写自己的库。 https://github.com/BrnoPCmaniak/django-egfk 所以现在我可以这样做:

class Main(models.Model):
    content_type = models.ForeignKey(
        ContentType, on_delete=models.CASCADE, blank=True, null=True)


class Child(models.Model):
    object_id = models.PositiveIntegerField()
    main = models.ForeignKey(Main, related_name="child")
    content_object = EnhancedGenericForeignKey('main.content_type', 'object_id')

使用示例:

>>> from test_egfk.models import Main, Child, TestSampleModel
>>> m = Main()
>>> print(m.content_type)
None
>>> m.save()
>>> t = TestSampleModel(text="Test")
>>> t.save()
>>> t.text
'Test'
>>> c = Child(main=m, content_object=t)
>>> c.save()
>>> Main.objects.last().content_type
<ContentType: test sample model>
>>> c.content_object
<TestSampleModel: TestSampleModel object>