Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to save availability of user over days of week in python/django

Tags:

python

django

I want to store users preferences for day(s) of week he might be available. e.g. A user can be available on saturday, sunday but not on other days. Currently I am using array of 7 checkboxes(values=1,2,...7) so that user can select individual days of his availability.

Now the first question is how can i store this in database. I am thinking of using a string(length=7) and storing preferences like 1100010 where 1 will signify available and 0 not available. Is it good practice?

Second question, how can I convert POST data (["1","2","7"]) into string (1100010)

like image 934
Myth Avatar asked Mar 02 '11 13:03

Myth


2 Answers

1st - good solution, I'm doing mine similarly. 2nd - you should think of assigning each day power of 2, that way it'll be easy to convert those numbers to binary using bin() and easy to compare you'll just do &.

>>> mon, tue, wed, thu, fri, sat, sun = (pow(2, i) for i in range(7)) 
>>> bin(mon)
'0b1'
>>> bin(sun)
'0b1000000'

# create range:
>>> x = mon | wed | fri
>>> bin(x)
'0b10101'

# check if day is in range:
>>> x & mon
1
>>> x & tue
0

The problem with bin is that you must add 0's to the beginning to get 7 char long string, but you could also write your own version like this:

bin = lambda n:"".join([str((n >> y) & 1) for y in range(7-1, -1, -1)]) 
like image 107
soltysh Avatar answered Sep 29 '22 00:09

soltysh


I found this implementation of a BitField by David Cramer, which should do what you want. Looks very nice.

like image 26
Daniel Roseman Avatar answered Sep 29 '22 02:09

Daniel Roseman