ChoiceField for Django models
Project description
Django ChoiceField
Motivation
Have you also felt annoyed by having to convert Django's enumeration types back to its type? Using tricks seen below to cast it.
class Suit(models.IntegerChoices):
DIAMOND = 1
SPADE = 2
HEART = 3
CLUB = 4
class Card(models.Model):
suit_kind = models.IntegerField(choices=Suit.choices, db_column="suit")
@property
def suit(self) -> Suit:
return Suit(self.suit_kind)
This is what django-choicefield
helps out with. While it additionally supports using
Python's native enum.Enum to express
column values.
Features
Using Django's enumeration types
import choicefield
from django.db import models
class Suit(models.IntegerChoices):
DIAMOND = 1
SPADE = 2
HEART = 3
CLUB = 4
class Card(models.Model):
suit = choicefield.ChoiceField(Suit)
instance = Card.objects.create(suit=Suit.CLUB)
assert instance.suit is Suit.CLUB
There's also support for Django's models.TextChoices
.
Using Python's native enumeration
import choicefield
from enum import Enum
from django.db import models
class Suit(int, Enum):
DIAMOND = 1
SPADE = 2
HEART = 3
CLUB = 4
class Card(models.Model):
suit = choicefield.ChoiceField(Suit)
instance = Card.objects.create(suit=Suit.DIAMOND)
assert instance.suit is Suit.DIAMOND
Passing enum values
It's also possible to pass the value of an enum, which will be converted to its corresponding enum instance.
instance = Card(suit=2)
assert instance.suit is Suit.SPADE
instance.save()
assert instance.suit is Suit.SPADE
instance = Card.objects.get(suit=2)
assert instance.suit is Suit.SPADE
Getting stored database values
If you want to access the stored database values, without conversion to your enum type,
you can use the registered __raw
transformer.
Cart.objects.values("suit__raw")
# <QuerySet [{'suit__raw': 2}]>
Installation
Using pip
$ pip install django-choicefield
Running tests
Running the whole test matrix
$ tox
Running the test suite for one environment
e.g. Django==4.0.x
and Python3.11
$ tox -e django40-py311
Compatibility
django-choicefield
is tested according to the table below
Django version | Python version |
---|---|
4.1.x | ^3.10 |
4.0.x | ^3.10 |
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django_choicefield-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d0e20b835eb16fb7ef31619fbda0cdb00c2e7aebafd3e2f4f233258177449567 |
|
MD5 | c27ac99df246e1cea1c945646c147672 |
|
BLAKE2b-256 | beb1e2ec76945e5036cba1b039071efc52db3cc34446742cba73978747cf137d |