具有计算内容类型而不是fk到内容类型模型的通用外键

时间:2017-08-23 06:17:35

标签: django django-models django-contenttypes generic-foreign-key

创建通用外键的最简单情况如下:

class ModelWithGFK(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

但在我的情况下还有其他字段可以推断出内容类型,因此添加content_type FK既冗余又容易导致一段时间不一致。所以我尝试了这个:

class ModelWithGFK(models.
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    @property
    def content_type(self):
        # Figure out wich content type this instance should have FK to
        return ContentType.objects.get(..........)

但似乎GFK类只接受内容类型参数作为外键:

def _check_content_type_field(self):
    """
    Check if field named `field_name` in model `model` exists and is a
    valid content_type field (is a ForeignKey to ContentType).
    """

是否存在一种解决方法(可能通过覆盖GFK及其某些方法,如get_content_type)或我将屈服,添加FK并生活在一直担心不一致和痛苦的了解这个(微小的)不可避免的冗余?

0 个答案:

没有答案