I
I
Ilya2017-04-27 10:32:15
Django
Ilya, 2017-04-27 10:32:15

How to check the manytomany field for the presence of an object in it?

There is a user model, and a product

class User(AbstractBaseUser):
  purchased = models.ManyToManyField('Movie', verbose_name='Купленные товары', blank=True)

class Movie(models.Model):
  title = models.CharField(verbose_name='Название', max_length=100)

How can I check if there is a video in the purchased field?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pinkevich, 2017-04-27
@nuBacuk

As an option

movie1 = Movie.objects.get(pk=1)
movie2 = Movie.objects.get(pk=2)
User.objects.filter(pk=1, purchased__in=[movie1, movie2]).exists()

or
movie = Movie.objects.get(pk=1)
user = User.objects.get(pk=1)
user.purchased.filter(pk=movie.pk).exists()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question