Abdur Rehman
Abdur Rehman

Reputation: 114

querying using Q objects and also using Q single object

i have 2 queries which i have to join using '|' and apply the final one to get the result.First i have list of countries i.e eu countries.and second i have a country from which the user is logged in.I want to join both ones and get the result using Q.First one is q= Q(country=auth.country)and second one is
q2 = Q(country = settings.euCountries), in which settings.enCountries is a django list.Any help in this matter is highly appreciated

Upvotes: 0

Views: 30

Answers (2)

itzMEonTV
itzMEonTV

Reputation: 20369

If you need an OR for all countries

q = [Q(country=auth.country)] + [Q(country=i) for i in settings.euContries]

Then

import operator
Model.objects.filter(reduce(operator.or_, q))

Upvotes: 2

Alasdair
Alasdair

Reputation: 309109

I don't think you need multiple Q() objects here. You can use the __in lookup.

Q(country_in=[auth.country] + settings.euCountries)

Depending on your code, you might not need the Q object at all if you can do something like the following:

queryset = MyModel.objects.filter(country_in=[auth.country] + settings.euCountries)

Upvotes: 1

Related Questions