0

First time post here :) I'm learning python and the django framework through a simple photo album app. I'm working through the admin site only for now, and django is v.2.1.

There's a photo-album table and an images table. A photo album can have many images and an image can be associated with many photo albums, so I modelized a many-to-many relation through an intermediary table.

My photo album change page has an inline for the images in it. All this is straightforward and works well.

Apart from the two parent tables PKs, the intermediary table has an extra boolean field, "isCover", so that a user can select an image in the photo album to act as a cover. However, in the inline there is no way to enforce only one image is checked as cover. Plus, I'd like the functionality that the first image be automatically selected as cover if the user selects none.

How can that be accomplished?

Thanks in advance for any insights! Joe

Joe
  • 1
  • 2
  • Please add some code so that a developer can help you out. Please be precise then, where actually you are getting the problem. – Abhinav Saxena Oct 15 '18 at 06:16

1 Answers1

0

You can create the intermediate table using through keyword in many to many fields:

 class Album(models.Model):
     name = models.CharField(max_length=100)
 class Image(models.Model):
    image = models.ImageField()
    album = models.ManyToManyField(Album, through=AlbumImage)

 class AlbumImage(models.Model):
  image = models.ForeignKey(Image)
  album = models.ForeignKey(Album)
  is_cover = models.BooleanField()
Wes
  • 954
  • 13
  • 25
aman kumar
  • 3,086
  • 1
  • 17
  • 24
  • Thanks Aman for taking the time to answer. The intermediate table is created, exactly like you show. The problem is, for a given album I can't enforce that only one of the child has is_cover to true - A user can set them all to true or all to false. – Joe Oct 15 '18 at 09:03
  • no you can setr the one imgae as cover true, for ex album a with image x is covet, AlbumImage.objects.filter(image=z, album=a).update(is_cover=True) – aman kumar Oct 15 '18 at 10:33
  • Ok so no built-in way, have to do a little validation code. No big deal, but I'd like to do that on the model-level. I'm investigation the various validators available there. Thanks for your help! – Joe Oct 16 '18 at 00:35