djangoimagefielddjango-imagekit

Django, two ImageField pointing to the same file


I'd like my two image fields point to the same image.

At one time, I'll have one image field populated.
At later time, I'd like another imageField to point to the same file.

(If the first one changes, the second one gets updated as well)

The file is at amazon s3 if it matters.

I could use django-imagekit.


Solution

  • I would do it with a structure like this:

    class Image(models.Model):
        img = models.ImageField(upload_to = "images", related_name="+")
    
    class A_model(models.Model):
        image = models.ForeignKey(Image)
    
    class B_model(models.Model):
        image = models.ForeignKey(Image)
    

    This avoids redundancies in the database, which you would have using two image fields. And access to the image is quite easy.

    Note that you have to set the related to "+", because Django cannot reverse the relation in this case.