【问题标题】:Single filter with ManyToMany queryset on DjangoDjango上带有ManyToMany查询集的单个过滤器
【发布时间】:2016-04-11 20:45:09
【问题描述】:

我想根据来自不同模型的多字段执行一些过滤,但是卡住了。

我有这些模型

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)

因此,根据我的用户选择的类别(Userlogin 类),我想过滤事件。 示例:

Userlogin 80 has choose ['openair','night']

Events:

Event 1 - ['openair','couples']

Event 2 - ['couples']

Event 3 - ['night','openair']

这应该返回事件 1 和 3。

所以我有一个包含其他评估的查询集,现在我想将用户类别与事件类别“加入”。

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 

我怎么能这样做?这里的诀窍是我需要继续使用这个查询集,所以我想使用 filter 方法。

我正在使用 django 1.9

【问题讨论】:

    标签: django django-queryset


    【解决方案1】:
    # returns all the events which have any of the user_login categories
    events = events.filter(category__in=user_login.category.all()).distinct()
    

    django 文档提供了有关跨模型查询 m2m 关系的详细信息。见https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 2014-04-18
      • 1970-01-01
      相关资源
      最近更新 更多