Maps
Maps

Reputation: 135

Query on BooleanFields using string representations of the fields

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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

Related Questions