G
G
gh0sty2019-12-21 23:49:26
Django
gh0sty, 2019-12-21 23:49:26

How to create a filter from ManyToMany and contains in Django?

I have these models:

class Model1(models.Model):
    ...
class Model2(models.Model):
    m2m_field = models.ManyToManyField(Model1)

In views I get the following data:
m1 = Model1.object.get(...) #он просто у меня есть
m2 = Model2.objects.all()

How can I create a filter like :
x = m2.filter(m2m_field__contains=m1)
Well, the trick is that it won’t work like that, but doing it in a cycle is wildness, big data. I googled a lot, in is also not right.
Tipo to select instances in which m2m contains this object m1.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
antonksa, 2019-12-22
@gh0sty

Wrong doctor's decision.
Need like this:

class Model2(models.Model):
    m2m_field = models.ManyToManyField(to=Model1, related_name='second_models')

And than:
m1 = Model1.object.get(...) #он просто у меня есть
second_model_queryset = m1.second_models.all()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question