Django: union of different queryset on the same model

前端 未结 2 928
日久生厌
日久生厌 2021-01-15 17:15

I\'m programming a search on a model and I have a problem.

My model is almost like:

class Serials(models.Model):
    id = models.AutoField(primary_ke         


        
相关标签:
2条回答
  • 2021-01-15 17:48

    You should also be able to do qs1 | qs2 | qs3 | qs4. This will give you duplicates, however.

    What you might want to look into is Q() objects:

    from django.db.models import Q
    value = "new"
    Serials.objects.filter(Q(name__startswith=value) |
                           Q(code__startswith=value) |
                           Q(name__contains=value) |
                           Q(code__contains=value).distinct()
    

    I'm not sure if it will handle the ordering if you do it this way, as this would rely on the db doing that.

    Indeed, even using qs1 | qs2 may cause the order to be determined by the db. That might be the drawback (and reason why you might need at least two queries).

    0 讨论(0)
  • 2021-01-15 17:54

    You can make those four queries and then chain them inside your program:

    result = itertools.chain(qs1, qs2, qs3, qs4)
    

    but this doesn't seem to nice because your have to make for queries.

    You can also write your own sql using raw sql, for example:

    Serials.objects.raw(sql_string)
    

    Also look at this:

    How to combine 2 or more querysets in a Django view?

    0 讨论(0)
提交回复
热议问题