Search code examples
pythondjangodjango-modelsgeneric-foreign-key

How to differentiate multiple GenericForeignKey relation to one model?


I have the following model structure:

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)

I wonder how I can tell that one file was uploaded as a picture_before and another as picture_after. The Uploadable does not contain any information about it.

Googled around for some time but did'nt find a proper solution.


Solution

  • It seems there is only one way to do it. You'll need to create an additional attribute in the generic model so you can persist the context.

    I got the idea 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')