微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django ContentType 与许多模型的关系

如何解决Django ContentType 与许多模型的关系

我正在研究假设与许多不同模型相关的模型,但一个实例应该只与这些模型中的一个相关。像模型响应一样,它应该存储在字段上解析的响应正文,但此响应可以来自具有不同字段集的不同站点

搜索 SO 我发现使用 django GenericRelation 是一个很好的方法,所以我尝试如下:

class Response(models.Model):
   content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
   object_id = models.PositiveIntegerField()
   service_data = GenericForeignKey("content_type","object_id")

class ServiceOne(models.Model):
    field1 = models.CharField(...)

class ServiceTwo(models.Model):
    field2 = models.CharField(...)

对于这些模型,我想做这样的事情:

s1 = ServiceOne.objects.create(field1="Foo")
s2 = ServiceTwo.objects.create(field1="Bar")
r1 = Response.objects.create(service_data=s1)
r2 = Response.objects.create(service_data=s2)

但它正在抛出 django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint

诸如“添加 null=True”(如此处 Django Make ContentType Not Required)之类的解决方案不是我所期望的,因为我希望这种关系成为,而不是摆脱错误本身。

根据https://docs.djangoproject.com/en/3.2/ref/contrib/contenttypes/,它应该可以正常工作,但我想我错过了一些东西。

我尝试将其添加到 ServiceOne 和 ServiceTwo

    response = GenericRelation(
    Response,content_type_field='content_type_fk',object_id_field='object_primary_key',)

model_type = ContentType.objects.get(
app_label='actual_app_label',model="serviceone"
)
s1 = ServiceOne.objects.create(field1="Foo")
r1 = Response.objects.create(
    service_data=s1,content_type=model_type,)

但它没有给出任何不同的结果。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。