Search code examples
djangomodels

Selecting a favourite image from a list of associated images in Django Models


I have the following AlbumImage model which is for the images my users upload:

`

class AlbumImage(models.Model):
    image = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70})
    alt = models.CharField(max_length=255, default=uuid.uuid4)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=70, default=uuid.uuid4, editable=False)

`

and the model of people who might appear in the aforementioned pictures:

`

class People(models.Model):
    name = models.CharField(max_length=30,default='John Doe')
    remind_on = models.DateField()
    event = models.TextField(default='No Event')
    associated_with = models.ManyToManyField(AlbumImage)

`

Problem: I want my user to be able to select one of the images from the many associated images. How do I represent that in my models?


Solution

  • You can use a OneToOneField as follows,

    class People(models.Model):
        name = models.CharField(max_length=30,default='John Doe')
        remind_on = models.DateField()
        event = models.TextField(default='No Event')
        associated_with = models.ManyToManyField(AlbumImage)
        favourite_image = models.OneToOneField(AlbumImage)