Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary comprehension with Q

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?

like image 255
ZmuA Avatar asked Mar 05 '26 02:03

ZmuA


1 Answers

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.

like image 137
Wander Nauta Avatar answered Mar 07 '26 14:03

Wander Nauta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!