Django excluding specific instances from queryset without using field lookup

后端 未结 4 908
南笙
南笙 2020-12-23 14:13

I sometimes have the need to make sure some instances are excluded from a queryset.
This is the way I do it usually:

unwanted_instance = MyModel.object         


        
相关标签:
4条回答
  • 2020-12-23 14:30

    The Given answer is perfect and try this which works fine for me

    step 1)

     from django.db.models import Q
    

    step 2)

     MyModel.objects.filter(~Q(id__in=[o.id for o in <unwanted objects>]))
    
    0 讨论(0)
  • 2020-12-23 14:33

    The way you're already doing it is the best way.

    If it's a model-agnostic way of doing this you're looking for, don't forget that you can do query.exclude(pk=instance.pk).

    Just as an aside, if Django's ORM had an identity mapper (which it doesn't at present), then you would be able to do something like MyModel.objects.filter(<query>).all().remove(<instance>), but you're out of luck in that regard. The way you're doing it (or the one above) is the best you've got.

    Oh, and also you can do much better than that in query with a list comprehension: query.exclude(id__in=[o.id for o in <unwanted objects>])

    0 讨论(0)
  • 2020-12-23 14:36

    you can use "~" with Q Lookup

    for example, the following query will get all tickets from ticket model, except TKT_STATUS field that marked as a "solved" status :

    from django.db.models import Q
    
    queryset_list = ticket.objects.filter(~Q(TKT_STATUS__iexact="solved"))
    
    0 讨论(0)
  • 2020-12-23 14:44

    You can put your unwanted items in a list , and a fetch all items except those in the list like so:

    MyModel.objects.exclude(id__in=[id1,id2,id3 ])
    
    0 讨论(0)
提交回复
热议问题