Issue
I have Dog model which has name and color, and i have list of tuples that contains (name, color) of dogs that I want to exclude. How can I achieve a queryset that would be filter dogs that not exist in that list?
class Dog(BaseModel):
name = models.CharField(max_length=255)
color = models.CharField(max_length=255)
Dog.objects.all()
>> [<Dog: name='Lucky', color='Brown'>, <Dog: name='Lucky', color='White'>, <Dog: name='Maple', color='Brown'> ,<Dog: name='Maple', color='Black'>, <Dog: name='Maple', color='White'>]
_list = [('Maple', 'White'), ('Lucky', 'Brown')]
What im looking for is something like that:
Dog.objects.custom_exclude(_list)
>> [<Dog: name='Lucky', color='White'>, <Dog: name='Maple', color='Brown'> ,<Dog: name='Maple', color='Black'>]
Solution
This should do the job.
import operator
from functools import reduce
from django.db.models import Q
exclude_params = reduce(operator.or_, [Q(name=name, color=color) for name, color in list])
Dog.objects.exclude(exclude_params)
Answered By - Mohit Solanki
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.