Django object multiple exclude()

后端 未结 5 2186
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 22:20

Is there a way to do a query and exclude a list of things, instead of calling exclude multiple times?

5条回答
  •  無奈伤痛
    2020-12-30 22:38

    You can do it pretty easily with the Q object:

    from django.db.models import Q
    
    excludes = None
    for tag in ignored_tags:
        q = Q(tag=tag)
        excludes = (excludes and (excludes | q)) or q # makes sure excludes is set properly
    set_minus_excluded = Foo.objects.exclude(excludes)
    

    You should also be able to do it dynamically with exclude():

    qs = Foo.objects.all()
    for tag in ignored_tags:
        qs = qs.exclude(tag=tag)
    

提交回复
热议问题