Single filter with ManyToMany queryset on Django
I want to perform some filter based on manytomany fields from different models, but am stuck.
I have these models
class Category(models.Model):
eventtype = models.CharField(max_length=10, choices=event_type)
category = models.CharField(max_length=60)
values = models.CharField(max_length=60,null=True, blank=True)
class Userlogin(models.Model):
name = models.CharField(max_length=100, null=True)
category = models.ManyToManyField(Category)
class Events(models.Model):
eventtype = models.CharField(max_length=4)
status = models.CharField(max_length=1, choices=status, verbose_name='Status', default='I')
category = models.ManyToManyField(Category)
So based on the categories my user choose (Userlogin class), I want to filter the events. Example:
Userlogin 80 has choose ['openair','night']
Events:
Event 1 - ['openair','couples']
Event 2 - ['couples']
Event 3 - ['night','openair']
That should return Events 1 and 3.
So I have a queryset that has some other evaluations, and now I want to "join" the user categories with the Events categories.
events = Events.object.filter(status='A')
events = events.filter(eventtype='X)
#some other complex filtering, based on other models
events = events.filter(category??????) #stuck here
How could I do that? The trick here is that I need to keep using this queryset, so I would like to go with the filter method.
I am using django 1.9
# returns all the events which have any of the user_login categories
events = events.filter(category__in=user_login.category.all()).distinct()
The django documentation provides details on querying m2m relationship across models. See https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/
链接地址: http://www.djcxy.com/p/38656.html上一篇: Django中的“slug”是什么?