How to perform OR condition in django queryset?

前端 未结 4 1804
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 07:39

I want to write a Django query equivalent to this SQL query:

SELECT * from user where income >= 5000 or income is NULL.

How to construct

4条回答
  •  被撕碎了的回忆
    2020-12-07 08:04

    Because QuerySets implement the Python __or__ operator (|), or union, it just works. As you'd expect, the | binary operator returns a QuerySet so order_by(), .distinct(), and other queryset filters can be tacked on to the end.

    combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
    ordered_queryset = combined_queryset.order_by('-income')
    

    Update 2019-06-20: This is now fully documented in the Django 2.1 QuerySet API reference. More historic discussion can be found in DjangoProject ticket #21333.

提交回复
热议问题