gpt4 book ai didi

python - 多个模型上的 Django GenericForeignKey 字段

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:35 25 4
gpt4 key购买 nike

有没有一种方法可以让 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')

最佳答案

我必须为它编写自己的库。 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>

关于python - 多个模型上的 Django GenericForeignKey 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38808617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com