What's the best way to represent many booleans in a django model?


What's the best way to represent many booleans in a django model?



I have a model which represents the user's display preferences. Just about all of these preferences are boolean values. Instead of having 50 boolean columns, is there a better way to go about this? In the future when I want to add a new item, I don't want to have to add a new column in my database.




Django, register user with first name and last name?

1:



Create a PDF or Printable version of change_list.html in Django Admin
" In the future when I want to add a new item, I don't want to have to add a new column in my database.".
ImportError for django.contrib.markup
In this case, you'll want to add a row.


Django inlines, how i know which was edited?
.
Filtering on related objects when using annotations in Django
You have a table with the domain of possible setting Names.


Django preview, TypeError: 'str' object is not callable
50 rows..
Checking for empty queryset in Django
You have a table of actual settings.


Querying django ManyToMany
User, Setting Name, Setting Value..


2:


You could also use a bitmap.

You only need single char field in you database.

Somewhere in your app you store a list of preferences, pref1, pref2, pref3 ...

and in the bitmap filed you store a sequence of 1's and 0's that correspond to the preferences.. For example 101 means pref1=yes, pref2=no, and pref3=yes and 011 means pref1=no, pref2=yes, and pref3=yes.. You could make this reusable by creating a new model field type for bitmaps..


3:


If you have that many booleans and are anticipating adding more, you should not be using columns, but entries.



Then when you need to look up "User wants emails", just search for UserPrefs.objects.get(User=user, Preference=Preferences.objects.get(name="wants email")).



User_Table:.
  • User
  • username
  • etc
Preferences_Table:.
  • name
  • description
  • etc
UserPreferences_Table:.
  • User (FK_User)
  • Preference (FK_Preferences)
  • Setting (Boolean)
Depending on your setup, you may be able to omit the Setting field in the UserPreferences table and simply use the existence of an entry for that User/Preference as a True and the lack of one as a False..



98 out of 100 based on 58 user ratings 1358 reviews

@