Opened 8 years ago

Closed 8 years ago

#27239 closed Bug (duplicate)

Unexpected behavior on get_FIELDNAME_display when as int as value

Reported by: Levi Velázquez Owned by: nobody
Component: Database layer (models, ORM) Version: 1.10
Severity: Normal Keywords: choice, field
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Let's say we have have a choice field called gender and it has intengers as values.

    GENDER_CHOICES = (
        (1, _('Male')),
        (2, _('Female'))
    )

gender = models.CharField(choices=GENDER_CHOICES, null=True)

If we create an instance with a gender as 1 or '1' and then try to display gender field value using get_FIELDNAME_display method, we will get unwanted value. We will get '1' and not 'Male' as it supposed to be.

Model.instance.create(gender=1)
instance.get_gender_display()
>>>'1'


The correct response should be

Model.instance.create(gender=1)
instance.get_gender_display()
>>>'Male'

Change History (3)

comment:1 by Claude Paroz, 8 years ago

Why would you use integer values for a CharField in the first place?

in reply to:  1 comment:2 by Levi Velázquez, 8 years ago

Replying to claudep:

Why would you use integer values for a CharField in the first place?

Because it's possible. If Django allows you to assign it, so, it should take care of that case.

comment:3 by Tim Graham, 8 years ago

Resolution: duplicate
Status: newclosed

Duplicate of #20749 which suggests to add a system check to prohibit using incorrect types in choices.

Note: See TracTickets for help on using tickets.
Back to Top