Reputation: 135
How can I filter on the boolean fields of a model, given a string representation of the attribute, taken to mean true for that attribute?
As an example, given:
class MealBooking(models.Model):
breakfast = models.BooleanField()
lunch = models.BooleanField()
dinner = models.BooleanField()
meal = "breakfast"
How can I filter on all MealBookings containing True
for the field represented by meal
?
Upvotes: 1
Views: 49
Reputation: 476594
You can filter with:
MealBooking.objects.filter(**{meal: True})
We thus first create a dictionary. If meal
is for example 'breakfast'
, the dictionary will look like { 'breakfast': True }
.
Then we unpack the dictionary to named parameters, by adding two asterisks (**
) in front. This thus means that if the dictionary is { 'breakfast': True }
, we call .filter(…)
with .filter(breakfast=True)
.
Upvotes: 1