多个条件下的标签搜索

时间:2018-06-27 09:32:35

标签: django django-models django-orm

我想获取所有配置文件,其中tag ='hello'和tag ='world'。我尝试使用Q()查询,但结果不正确。

models.py

class Tag(models.Model):
    name = models.CharField(unique=True, max_length=100)
    slug = models.SlugField(unique=True, max_length=100)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['slug']


class Profile(models.Model):
    name = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

views.py

def search(request: HttpRequest):
    q_tag_list = request.GET.get('search-tag').split(',')
    profile_filter = Q()
    for tag in q_tag_list:
        profile_filter = profile_filter & Q(tags__slug__startswith=tag)
    profiles = Profile.objects.filter(profile_filter)
    return render(request, 'list.html', {'profiles': profiles})

生成的sql(通过django调试工具栏)

SELECT "socialmedia_profile"."id", "socialmedia_profile"."name", "socialmedia_profile"."facebook_name", "socialmedia_profile"."facebook_latest_likes" FROM "socialmedia_profile" INNER JOIN "socialmedia_profile_tags" ON ("socialmedia_profile"."id" = "socialmedia_profile_tags"."profile_id") INNER JOIN "socialmedia_tag" ON ("socialmedia_profile_tags"."tag_id" = "socialmedia_tag"."id") WHERE ("socialmedia_tag"."slug" LIKE '''hello%''' ESCAPE '\' AND "socialmedia_tag"."slug" LIKE '''world%''' ESCAPE '\') ORDER BY "socialmedia_profile"."name" ASC

0 个答案:

没有答案