[Answered ]-How to choose one item in many to many relationship as special?

1👍

You can make a custom through=… model [Django-doc] with a boolean cover that is set to True in case it is the cover item:

from django.db.models import Q, UniqueConstraint

class Photo(models.Model):
  img = models.FileField()

class Album(models.Model):
  photos = models.ManyToManyField(Photo, through='AlbumPhoto')

class AlbumPhoto(models.Model):
    photo = models.ForeignKey(Photo, on_delete=models.CASCADE)
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    cover = models.BooleanField(default=False)
    
    class Meta:
        constraints = [
            UniqueConstraint(fields=['photo', 'album'], name='no_photo_multiple_times'),
            UniqueConstraint(fields=['album'], condition=Q(cover=True), name='one_cover_per_album'),
        ]

The first constraint guarantees that you can not add the same Photo multiple times to the same Album, whereas the second condition gurantees that each Album has at most one Photo for which cover=True.

Leave a comment