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

pkln4tw6  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(129)

我有以下模型结构:

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不包含任何有关它的信息。
在谷歌上搜索了一段时间,但没有找到合适的解决方案。

roejwanj

roejwanj1#

似乎只有一种方法可以做到这一点。您需要在通用模型中创建一个附加属性,以便能够持久化上下文。
我有个想法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')

相关问题