django dynamically filtering with q objects

后端 未结 4 1171
抹茶落季
抹茶落季 2020-12-04 17:48

I\'m trying to query a database based on user input tags. The number of tags can be from 0-5, so I need to create the query dynamically.

So I have a tag list, tag_li

4条回答
  •  再見小時候
    2020-12-04 18:49

    You'll want to loop through the tag_list and apply a filter for each one.

    tag_list = ['tag1', 'tag2', 'tag3']
    base_qs = Design.objects.all()
    for t in tag_list:
        base_qs = base_qs.filter(tags__tag__contains=t)
    

    This will give you results matching all tags, as your example indicated with and. If in fact you needed or instead, you will probably need Q objects.

    Edit: I think I have what you're looking for now.

    tags = ['tag1', 'tag2', 'tag3']
    q_objects = Q() # Create an empty Q object to start with
    for t in tags:
        q_objects |= Q(tags__tag__contains=t) # 'or' the Q objects together
    
    designs = Design.objects.filter(q_objects)
    

    I tested this and it seems to work really well.

    Edit 2: Credit to kezabelle in #django on Freenode for the initial idea.

提交回复
热议问题