0

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?

1 Answers1

0

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)
Josewails
  • 570
  • 3
  • 16
  • Tha's what I originally thought of, but I want the favourite_image to be one of the images in associated_with images. This wouldn't corroborate that. – Nimish Verma Jul 11 '18 at 14:34
  • I get it. This is not the way to do it. Have a look at [this](https://stackoverflow.com/questions/7133455/django-limit-choices-to-doesnt-work-on-manytomanyfield). If you still can't implement it, Let me know. I will update my answer. – Josewails Jul 11 '18 at 14:46
  • I found a way around it by adding a ForeignKey Field and giving it overriding the save function to make the 0th element of the list of associated_with images as the favourite image. I have also added another function which will allow user to change the favourite, I will make sure he can only select the associated_with images in the front end. – Nimish Verma Jul 11 '18 at 19:44
  • I have seen the link and they have somewhat handled it in a similar fashion by overriding __init__ function. Appreciate the help! – Nimish Verma Jul 11 '18 at 19:46