Django Custom Queryset filters

前端 未结 2 813
刺人心
刺人心 2021-02-09 03:55

Is there, in Django, a standard way to write complex, custom filters for QuerySets?

Just as I can write

MyClass.objects.all().filter(field=val)
<         


        
相关标签:
2条回答
  • 2021-02-09 04:13

    I think you may need custom managers.

    0 讨论(0)
  • 2021-02-09 04:36

    The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use Q objects. For example:

    from django.db.models import Q
    
    complexQuery = Q(name__startswith='Xa') | ~Q(birthdate__year=2000)
    
    MyModel.objects.filter(complexQuery)
    

    Q objects can be combined with | (OR), & (AND), and ~ (NOT).

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