How to organize my models in the construction of a photo album in Django?

Asked

Viewed 173 times

3

I’m building a photo album, but I don’t know how I should organize it. How my models should 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)
  • You want each photo to belong to more than one album or not?

  • @bfavaretto in this case no

  • I don’t know anything about Jango, but it seems that the only difference is this: the first format defines that a photo can be in several albums, and the second says that it belongs to one. But I’m not going to post this as an answer because I’m not sure, I’m going to leave it to some expert on the subject to say,.

1 answer

2


It 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 can be 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 the results on both sides.

Example (for code 2):

To get a list of photos that has album id equal to 1, you can do so:

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

Case 2

Regarding the structure below, you are saying that a photo can 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 for Album or vice versa. I recommend reading the Documentation of Django, or of djangobook.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.