Skip to content Skip to sidebar Skip to footer

Filter Using Exact With A Many_to_many Field Django Model

I have this definitions into models.py: class Group(models.Model): created = models.DateTimeField(auto_now_add=True) products = models.ManyToManyField(Product, through='Pro

Solution 1:

So you are fetching one entry with this line:

group = Group.objects.all()[0]

Now if you want to get the products for group you have to do it like this:

group.products.all()

If you do only:

group.products

you'll get only an instance of ManyRelatedManager.

Try to change the filter query:

Group.objects.filter(products__exact=group.products.all())

It should do the job.

EDIT:

You can further enhance the query and exclude the group that serves as searching reference:

Group.objects.filter(products__exact=group.products.all()).exclude(id=group.id)

UPDATE:

Usually when I query many2many relations, I use list of ids. In this case it could be done like this:

group = Group.objects.all()[0]
# or maybe better
group = Group.objects.all().first()
product_ids = list(group.products.all().values_list('id', flat=True))
Group.objects.filter(products__exact=product_ids)

Although I'm not sure if this is going to change anything.

Post a Comment for "Filter Using Exact With A Many_to_many Field Django Model"