[Answer]-OR in django database queries

1👍

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.

👤jdi

Leave a comment