Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store list of images in django model

I am building a Django data model and I want to be able to store an array of ImageFields. Is it possible?

mainimage = models.ImageField(upload_to='img', null = True)
images = models.??

Thanks.

like image 444
k3lf Avatar asked Jul 16 '13 09:07

k3lf


2 Answers

Create another model to images and have foreignkey with your model.

def YourModel(models.Model):
    #your fields

def ImageModel(models.Model):
    mainimage = models.ImageField(upload_to='img', null = True)
    image = models.ForeignKey(YourModel, ...)
like image 178
Rohan Avatar answered Oct 04 '22 01:10

Rohan


I would use the ManyToMany relationship to link your model with an image model. This is the way to aggregate ImageField as django does not have aggregate model field

def YourModel(models.Model):
    images = ManyToManyField(ImageModel)
    ...

def ImageModel(models.Model):
    img = ImageField()
    name ...

Maybe you need something more performant (this could lead to lots of horrible joins)

like image 24
bambata Avatar answered Oct 04 '22 02:10

bambata