Home > Mobile >  How do I use HTTP status code enum as django model field choices?
How do I use HTTP status code enum as django model field choices?

Time:08-18

I would like one of my django models to have a field like this:

status = models.IntegerField(choices=Status, max_length=20)

but instead it would take directly from the HTTPStatus class

In the mean time I've been using this with some common status codes:

class ModelA(models.Model):
    class Status(models.IntegerChoices):
        OK = 200,
        CREATED = 201,
        BAD_REQUEST = 400,
        REQUEST_TIMEOUT = 408,
        INTERNAL_SERVER_ERROR = 500,
        SERVICE_UNAVAILABLE = 503

    id = models.CharField(max_length=200, primary_key=True)
    status = models.IntegerField(choices=Status, max_length=20, default=201)

CodePudding user response:

'choices' must be an iterable containing (actual value, human readable name) tuples.

# choices=HTTPStatus,                             # Change this
choices=[(s.value, s.name) for s in HTTPStatus],  # to this
  • Related