【问题标题】:Django M2M: get objects containing all elements of arrayDjango M2M:获取包含数组所有元素的对象
【发布时间】:2016-08-10 08:14:35
【问题描述】:

我正在尝试解决使用多对多关系获取对象的问题。问题如下:

我有一组选定的过滤器,比如说,[red, rounded]。然后我有一个包含很多过滤器值的产品模型,例如:red、blue、rounded、blank、big、small

我的目标是获得红色圆形

的产品

当我使用__in=[array] 时,它显然会导致那些产品是红色的,而那些是圆形的。

对我来说唯一可行的解​​决方案是使用:

products.objects.filter(fil=red).filter(fil=rounded).all()

但我想知道是否有任何方法不使用大量 filter(),因为所需的数量是不可预测的(例如,用户可以选择 [red, blue, white, rounded]。

【问题讨论】:

    标签: django python-2.7 django-models


    【解决方案1】:

    您可以使用Q objects 构建自定义查询。

    # Build the query for selected terms
    custom_query = None
    for term in selected_terms:
        query_for_term = Q(fil=term)
        # Keep and'ing(&) terms
        custom_query = custom_query & query_for_term if custom_query else query_for_term
    
    # Then filter using the query
    products.objects.filter(custom_query)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      相关资源
      最近更新 更多