Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model query, filtering with choices [closed]

I have a model field as below.

GENDER_IN_CHOISES = (
        (MALE, _('Male')),
        (FEMALE, _('Female')),
        (UNDEFINED, _('Undefined')),
    )
    gender = models.CharField(max_length=2, choices=GENDER_IN_CHOISES, default=UNDEFINED)

I am making queries with object filtering however below does not satisfy my needs.

Users.objects.filter(gender__contains='male')

Do you know a way to make queries to choice fields?

like image 550
Umut Gunebakan Avatar asked Oct 30 '22 12:10

Umut Gunebakan


1 Answers

if MALE and FEMALE are defined as 'ML' and 'FL', then the contains='male' or the case-insensitive version icontains='male' queries would be useless because the database fields contain 'ML' and 'FL'

Your query would be more along the lines of:

Users.objects.filter(gender__in=('ML', 'FL'))

But you should reuse your constants to keep the code DRY (Don't Repeat Yourself)

Users.objects.filter(gender__in=(MALE, FEMALE))

Or, exclude the undefined genders

Users.objects.exclude(gender=UNDEFINED)
like image 106
bakkal Avatar answered Nov 15 '22 04:11

bakkal