Django过滤列表和

问题描述:

因此,即时尝试做的是过滤对来自查询的列表并返回可能的选项。Django过滤列表和

我有三种模式:

class Category(models.Model): 
    title = models.CharField(max_length=60, unique=True) 

class Colors(models.Model): 
    title = models.CharField(max_length=40, unique=True) 

class Post(models.Model): 
    title = models.CharField(max_length=40) 
    colors = models.ManyToManyField(Color) 
    category = models.ForeignKey(Category) 
    is_active = models.BooleanField(default=True) 

现在我想要做的是以下几点:

  • 获取所有的帖子,其中IS_ACTIVE ==真
  • 获取其中的颜色都包含在所有的帖子查询
  • 获取所有帖子,其中类别与查询中的类别相同

我的尝试是这样的:

# to be able using multiple values like ?color=red&color=blue&color=yellow 
queryparams = dict(request.query_params.lists()) 

colors_list = [] 
categories_list = [] 

if 'color' in query_params: 
    colors_list = query_params['color'] 

if 'category' in query_params: 
    categories_list = query_params['category'] 

posts = Post.objects.filter(is_active=True) 

if colors_list: 
    for color in colors_list: 
     posts = posts.filter(colors__title=color) 

if categories_list: 
    for category in categories_list: 
     posts = posts.filter(category__title=category) 

colors_options = posts.order_by('colors__title').values_list('colors__title', flat=True).distinct() 
categories_options = posts.order_by('category__title').values_list('category__title', flat=True).distinct() 

选项部分目前不工作我怎么想它做的事。比方说,我有5个对象有下列颜色:

  1. 黑色,蓝色,白色,黄色
  2. 蓝色,红色,白色
  3. 红,白,黄
  4. 黑色,黄色

如果我会的color = red &颜色=搜索白色它应该给我以下选项:

  1. 黑色,蓝色,白色,黄色
  2. 蓝色,白色
  3. 白色,黄
  4. 黑色,黄色

蓝色,红色,白色,黄色,但它只返回一种颜色

是否还有更高效和惯用的方式来实现这一目标? 这只是一个片段,实际上有更多的选择,但我试图在这里保持清晰。

而不是做

if colors_list: 
    for color in colors_list: 
     posts = posts.filter(colors__title=color) 

尝试做的:

if colors_list: 
    posts = posts.filter(colors__title__in=colors_list) 

请参阅:django filter with list of values

+1

这将导致一个或过滤器。我需要一个AND。 这意味着该字段需要包含列表的所有值。 –