How do I organize my models in building a photo album in Django?

3

I'm building a photo album, but I do not know how to organize it. How should my models be?

Class Foto(models.Model):
    foto = models.ImageField(upload_to='img')

Class Album(models.Model):
    nome = models.CharField(max_length=100)
    fotos = models.ManyToManyField(Foto)

Or so:

Class Foto(models.Model):
    album = models.ForeignKey(Album)
    foto = models.ImageField(upload_to='img')

Class Album(models.Model):
    nome = models.CharField(max_length=100)
    
asked by anonymous 05.05.2014 / 23:03

1 answer

2

This will depend on what you want.

Case 1

If you want to indicate that an album has n photos and these photos can be in more than one album, the structure looks like this:

# codigo 1
Class Foto(models.Model):
    foto = models.ImageField(upload_to='img')

Class Album(models.Model):
    nome = models.CharField(max_length=100)
    fotos = models.ManyToManyField(Foto)

Or so:

# codigo 2
Class Foto(models.Model):
    foto = models.ImageField(upload_to='img')
    albums = models.ManyToManyField(Album)

Class Album(models.Model):
    nome = models.CharField(max_length=100)        

In both cases, you can filter results from both sides.

Example (relative to code 2):

To get a list of photos that have album id equal 1 , you can do this:

album = Album.object.get(pk=1)
album.foto_set.all()

Case 2

Regarding the structure below, you are saying that a photo may only belong to an album:

Class Foto(models.Model):
    album = models.ForeignKey(Album)
    foto = models.ImageField(upload_to='img')

Class Album(models.Model):
    nome = models.CharField(max_length=100)

The relationship can happen from Photo to Album or vice versa. I recommend reading Django Documentation , or from djangobook .

    
06.05.2014 / 04:12