如何区分多个 GenericForeignKey 与一个模型的关系?

How to differentiate multiple GenericForeignKey relation to one model?

我有以下模型结构:

class Uploadable(models.Model):    
    file = models.FileField('Datei', upload_to=upload_location, storage=PRIVATE_FILE_STORAGE)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')


class Inspection(models.Model):
    ...
    picture_before = GenericRelation(Uploadable)
    picture_after = GenericRelation(Uploadable)

我想知道如何判断一个文件上传为 picture_before 而另一个文件上传为 picture_afterUploadable 不包含任何关于它的信息。

用 Google 搜索了一段时间,但没有找到合适的解决方案。

感谢支持!

看来只有一种方法可以做到。您需要在通用模型中创建一个附加属性,以便您可以保留上下文。

我明白了from this blog post:

class Uploadable(models.Model):
   
    # A hack to allow models have "multiple" image fields
    purpose = models.CharField(null=True, blank=True)
    
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

class Inspection(models.Model):
    ...
    images = GenericRelation(Uploadable, related_name='inspections')
    ...
    
    @property
    def picture_before(self):
        return self.images.filter(purpose='picture_after')
    
    @property
    def picture_after(self):
        return self.images.filter(purpose='picture_after')