Moving to Django 3.0's Field.choices Enumeration Types

栏目: IT技术 · 发布时间: 6年前

内容简介:One of the headline features of Django 3.0 is itsPreviously, Django recommended defining some ‘constants’ on your model class to feed into

Moving to Django 3.0's Field.choices Enumeration Types

One of the headline features of Django 3.0 is its Enumerations for model field choices . They’re a nicer way of defining and constraining model Field.choices .

Previously, Django recommended defining some ‘constants’ on your model class to feed into choices . You would add these as separate class variables and combine them into a list of choices paired with their display strings:

from django.db import models

class Book(models.Model):
    UNPUBLISHED = 'UN'
    PUBLISHED = 'PB'
    STATUS_CHOICES = [
        (UNPUBLISHED, 'Unpublished'),
        (PUBLISHED, 'Published'),
    ]
    status = models.CharField(
        max_length=2,
        choices=STATUS_CHOICES,
        default=UNPUBLISHED,
    )

Then your other could use those constants, for example:

unpublished_books = Book.objects.filter(status=Book.UNPUBLISHED)

If you wanted to use the same set of values for multiple models, you would probably move to the module level:

from django.db import models

UNPUBLISHED = 'UN'
PUBLISHED = 'PB'
STATUS_CHOICES = [
    (UNPUBLISHED, 'Unpublished'),
    (PUBLISHED, 'Published'),
]


class Book(models.Model):
    status = models.CharField(
        max_length=2,
        choices=STATUS_CHOICES,
        default=UNPUBLISHED,
    )


class Pamphlet(models.Model):
    status = models.CharField(
        max_length=2,
        choices=STATUS_CHOICES,
        default=PUBLISHED,
    )

This leaves a bunch of constants related only by their position in the class or module. It’s a bit against The Zen of Python’s final edict:

Namespaces are one honking great idea – let’s do more of those!

It also leaves us missing some useful functionality. For example there’s no easy way to convert a value into its display label.

Packages like django-choices and django-enumfields exist to solve these problems. I’ve also seen a couple custom implementations of similar functionality on other projects.

Django 3.0 now provides a Choices class with two subclasses IntegerChoices and TextChoices . These extend Python’s Enum types with extra constraints and functionality to make them suitable for Field.choices .

To convert our example, we want to subclass TextChoices , because the values are strings stored in a CharField . We then define how names map to values and display labels as class attributes:

from django.db import models


class Status(models.TextChoices):
    UNPUBLISHED = 'UN', 'Unpublished'
    PUBLISHED = 'PB', 'Published'


class Book(models.Model):
    status = models.CharField(
        max_length=2,
        choices=Status.choices,
        default=Status.UNPUBLISHED,
    )


class Pamphlet(models.Model):
    status = models.CharField(
        max_length=2,
        choices=Status.choices,
        default=Status.PUBLISHED,
    )

We can test we converted correctly by checking no migration changes are detected:

$ python manage.py makemigrations --dry-run
No changes detected

If we had added, removed, or reordered any members, this would have been detected as changes in the fields. This is because the migration framework only sees the choices list generated by Status.choices , not the enumeration classes.

QuerySet filters can be updated to use the Choices class:

unpublished_books = Book.objects.filter(status=Status.UNPUBLISHED)

We can also convert values to their display labels easily:

In [2]: book = Book.objects.latest('id')

In [3]: Status(book.status)
Out[3]: <Status.UNPUBLISHED: 'UN'>

In [4]: Status(book.status).label
Out[4]: 'Unpublished'

Clearer and cleaner!

Fin

I hope this helps you enjoy this new Django 3.0 feature. The Enumeration types documentation covers a few more details and is worth a read.

Thanks to Shai Berger, Nick Pope, Marius Felisiak, Carlton Gibson, and all the others responsible for adding it (ticket #27910 ).

—Adam


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

奔跑吧 Linux内核

奔跑吧 Linux内核

张天飞 / 人民邮电出版社 / 2017-9-1 / CNY 158.00

本书内容基于Linux4.x内核,主要选取了Linux内核中比较基本和常用的内存管理、进程管理、并发与同步,以及中断管理这4个内核模块进行讲述。全书共分为6章,依次介绍了ARM体系结构、Linux内存管理、进程调度管理、并发与同步、中断管理、内核调试技巧等内容。本书的每节内容都是一个Linux内核的话题或者技术点,读者可以根据每小节前的问题进行思考,进而围绕问题进行内核源代码的分析。 本书内......一起来看看 《奔跑吧 Linux内核》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具