Django: “Soft” ForeignField without database integrity checks

前端 未结 6 1314
南旧
南旧 2021-02-05 17:05

I have a Django project that has multiple django \"apps\". One of them has models to represent data coming from an external source (I do not control this data).

I want m

6条回答
  •  不知归路
    2021-02-05 17:35

    I solved this by using a GenericForeignKey:

    thing_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)
    thing_object_id = models.UUIDField(default=uuid.uuid4, blank=True, null=True)
    
    thing = GenericForeignKey(ct_field='thing_content_type', fk_field='thing_object_id')
    

    On the plus side, it's out-of-the-box Django

    On the negative side, you have three additional attributes in your model.

    Additionally, reverse relations don't automatically work, but in my case, I'm okay with that.

提交回复
热议问题