尝试使用多个过滤器查询表

时间:2013-12-03 21:26:57

标签: mysql django

我正在尝试添加功能,以便用户可以为我的网站上的一组项目选择多个浏览过滤器(SDK)。我的代码返回与任何过滤器标记匹配的SDK。如何仅显示与所有标记匹配的SDK?

models.py

class AppSdks(models.Model):
    sdk_name = models.CharField(max_length=256)
    sdk_type = models.CharField(max_length=256)
    company_url = models.URLField(max_length=1024)
    logo = models.URLField(max_length=1024)
    description = models.TextField()
    ios = models.BooleanField()
    android = models.BooleanField()


class AppSdksTags(models.Model):
    sdk = models.ForeignKey(AppSdks)
    tag = models.CharField(max_length=128)

views.py
if request.method=="POST":
    all_tags = request.POST.getlist('filter_tags')
    for each_sdk in sdks:

    results=[]
    sdk_list=[]
    sdks = AppSdks.objects.all()
    for each_tag in all_tags:
        sdks = AppSdksTags.objects.filter(tag=each_tag).values_list('sdk',flat=True).distinct()
        for each_sdk in sdks:
            if each_sdk not in sdk_list:
                sdk_list.append(each_sdk)
    for each_sdk in sdk_list:
        sdk = AppSdks.objects.get(id=each_sdk)
        results.append(sdk)

1 个答案:

答案 0 :(得分:1)

连续filter条款。

sdks = AppSdks.objects.all()
for each_tag in all_tags:
    sdks = sdks.filter(appsdkstags__tag=each_tag)

最终将使用单个查询集,其中每个AppSdks实例都包含所有必需的标记。