How to filter with manytomany field?
I have model":
class MyModel(models.Model开发者_如何学JAVA):
field1 = ...
sites = models.ManyToManyField(Site, blank = True, null=True)
and i want to filter (site is a correct Site object):
qs = MyModel.objects.filter(field1=thing, sites__id=site.id)
but this doesn't work. I get all objects, even those who do not have an entry in the table.
or i tried:
qs = MyModel.objects.filter(field1=thing, sites__in=site)
but i get nothing. Ho to do it?
If i understand your question right you have a specific site
and your trying to filter
by that site. Then you should filter like this:
site = Site.objects.get(pk=1)
mymodel_for_site = MyModel.objects.filter(field1=thing, sites=site)
This should get all the MyModel instances for a particular site
Try to make it via MyModel object, i.e.:
object = MyModel.objects.get(field1=thing)
qs = object.sites.all()
Check django docs
精彩评论