Reputation: 4908
I have a model that has 3 BooleanFields, and I want to use a checkbox form to query the database. The output should be all the entries of the table that has as 1 at least one of the fields that where checked. Right now I ahve something like this:
f=mform.cleaned_data['F']
h=mform.cleaned_data['H']
s=mform.cleaned_data['S']
course_list=[]
course_list=Course.objects.filter(Q(F=f)|Q(H=h)|Q(S=s))
But this clearly doesn't work, as it always returns all the table. Basically I want to get all Course records where any of these fields are True. Any ideas?
Upvotes: 0
Views: 53
Reputation: 92647
Query: "select all Course records where (F is True OR H is True OR S is True)"
q_filter = Q()
if mform.cleaned_data['F']:
q_filter |= Q(F=True)
if mform.cleaned_data['H']:
q_filter |= Q(H=True)
if mform.cleaned_data['S']:
q_filter |= Q(S=True)
if q_filter:
course_list = Course.objects.filter(q_filter)
else:
course_list = Course.objects.none()
This is a pretty basic approach. It could be done in a fancier one line loop but I wanted to go for clarity here. You build up a Q object over time. In your example you are filtering for values that could be True or False, whereas you said what you wanted is to only filter records that have a given field with a True value.
Upvotes: 1