Let's say I have the following piece of code:
criteria = {'description': 'tt', 'hostname': '2'}
filters = Q()
{filters.add(Q(**{k+'__icontains': v}), Q.AND) for k,v in criteria.items()}
I can't figure out how to avoid doubling the outcome:
{<Q: (AND: ('description__icontains', 'tt'), ('hostname__icontains', '2'))>,
<Q: (AND: ('description__icontains', 'tt'), ('hostname__icontains', '2'))>}
I understand I should shift Q.AND somewhere, shouldn't I?
It looks like you're inspecting the resulting set from the set comprehension, which lists the same Q object (filters) twice, after it's been modified. That's actually not a problem - you don't use that resulting set anywhere - but it does look a bit surprising.
As an alternative, it should be possible to pass all the kwargs you want to Q() in one go:
criteria = {'description': 'tt', 'hostname': '2'}
filters = Q(**{k + '__icontains': v for k, v in criteria.items()})
That removes the need for the set comprehension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With