Opened 3 months ago

Closed 3 months ago

Last modified 3 months ago

#35562 closed Bug (invalid)

get_FOO_display() method gives choice instead of choice.label for unbound (not saved) model instances with enumeration choices

Reported by: Gerben Morsink Owned by: nobody
Component: Database layer (models, ORM) Version: 4.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Gerben Morsink)

class FooChoices(models.TextChoices):
    BAR = 'BAR', 'bar_with_drinks'

foo = Foo(bar=FooChoices.BAR)

foo.get_bar_display() -> I expect it to return 'bar_with_drinks' (=FooChoices.BAR.label), but it returns a 'FooChoices.BAR' object. 

This is opposed to when I get Foo out of the database, because then foo.get_bar_display() will return the FooChoices.BAR.label.

Change History (4)

comment:1 by Gerben Morsink, 3 months ago

Description: modified (diff)

comment:2 by Gerben Morsink, 3 months ago

Resolution: fixed
Status: newclosed

comment:3 by Natalia Bidart, 3 months ago

Resolution: fixedinvalid

Hello Gerben Morsink, thanks for your ticket, I understand that you have solved your issue? In that case the proper resolution here is invalid. Cheers!

comment:4 by Gerben Morsink, 3 months ago

Hi Natalia Bidart,
That's correct, I found the issue.

For reference: The problem was that I had CharField where the choices were a subset of the FooChoices (FooChoicesSubset). When I did set a choice on the model instance (FooChoices.BAR) that was in FooChoices, but not in FooChoicesSubset, the answer of get_bar_display() was the FooChoices.BAR object (which did have a label) on the unbound model instance. I expected it to return the label, but probably because it was not a "valid" choice it returned the FooChoices.BAR object. On saving it would have given an error, but I'm not saving the model instance.

I still think the behaviour could be improved, by either raising an error, or by showing the label, but I also see that it is a non-normal situation.

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