Search code examples
pythondjangoenumeration

Enumeration types in Django


I am trying to use enumeration types in Django but fell like I am not doing the right thing...

I am building an ebay-like webapp where my Listings are saved in the database with a .category attribute.

class Listing(models.Model):

    class Category(models.TextChoices):
        TOY = "TO", _("Toys")
        FASHION = "FA", _("Fashion")
        ELECTRONICS = "EL", _("Electronics")
        HOME = "HO", _("Home")
        OTHERS = "OT", _("Others")

    title = models.CharField(max_length=64)
    category = models.CharField(
        max_length=2,
        choices=Category.choices,
        default=Category.OTHERS,
    )

I referred to Django's documentation for the use of Enumeration types but there are some grey areas, as far as my understanding goes.

When I render a template to display a Listing, how do I pass the string value associated with the .category of my Listing?

I tried something like this:

return render(request, "auctions/listing.html", {
            "listing": listing,
            "category": Listing.Category[listing.category].label,
        })

Or can I access it through the "listing" variable? What I would like is for the browser to display Home for a listing with listing.category = "HO".


Solution

  • Whenever you use a field having choices, Django makes a method for you to use get_<field_name>_display, you can use it in your template like:

    {{ listing.get_category_display }}