I’ve been searching for an elegant way to represent a multi-select weekday field (Mon, Tues, Wed…) in a Django model. I was initially thinking of going integer field using bitwise math but I am not sure if this would be the way to go.
This would be a mostly-read field. I would want the Queryset method to be something like Entry.objects.get(weekdays__contains=MONDAY) Where MONDAY would be a constant.
Perhaps someone could come up with a better solution? Or maybe someone has done something similar and has some example code they could contribute?
This is an old question, but I thought I would show how it could be done reasonably simply in Django.
Here is a helper class for preparing your choices:
Define your model with a PositiveIntegerField, and the choices you would like:
This means you can access the values like this:
Now define your model with a
PositiveIntegerFieldand these choices:And your models are done. For queries, the following does the trick:
There may be a way to create a
Q()object subclass that neatly packages queries, so they look like this:Or even hack at a
F()subclass to create something like this:But I don’t have the time to explore that at the moment.
.whereworks fine and can be abstracted into a queryset function.One final consideration is that you might light to make a custom model field that converts the bit mask in the database to a list or set in Python. You could then use a
SelectMultiplewidget (orCheckboxSelectMultiple) to allow the user to select their values in the admin.