1👍
As far as I can understand, if choices are:
GENDER_CHOICES = (
(1, 'Male'),
(2, 'Female'),
(3, 'Other'),
)
Then you can use:
def your_view(request, gender):
if gender == "male" or gender = "Male" :
accounts = Account.objects.filter(gender=1)
elif gender == "female" or gender = "Female":
accounts = Account.objects.filter(gender=2)
else :
accounts = Account.objects.filter(gender=3)
As you mentioned in the comments,
If you have 20 choices:
def your_view(request, gender):
id_list = [0,1,2,3 ....... 19]
choice_list = ["choice 0","choice 1","choice 2","choice 3",....."choice 19"]
for i in range(20):
if gender == choice_list[i]:
accounts = Account.objects.filter(gender=i)
0👍
I’m going to assume that your model is called Account
and that you have a gender
field in it.
Since you are using numbers for your choices, you would do this:
male_accounts = Account.objects.filter(gender=1)
and you can get the rest using the same method.
Edit:
Since in your comment, you want to access them using
male_accounts = Account.objects.filter(gender='male')
you should change your GENDER_CHOICES
to:
GENDER_CHOICES = (
('male', 'Male'),
('female', 'Female'),
('other', 'Other'),
)
quoting Django’s official docs:
The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.
https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices
- Django: MultiChoiceField does not show saved choices added after creation
- Displaying Django error messages in templates? – Not working
- Creating Django pgSQL Query With COUNT , GROUP BY , INTERVAL and LIMIT
- Send html input to views.py in Django
Source:stackexchange.com