Django的TextChoices等枚举类型应使用`is`还是`==`比较?
Django TextChoices 成员比较:用
== 还是 is? Django的models.TextChoices工作方式与Python标准库的enum类似,但存在一些修改。Python官方推荐使用身份运算符is比较枚举成员:
>>> Color.RED is Color.RED True
但Django文档并未明确说明TextChoices值的比较方式,针对以下两种写法,哪种更推荐?
from django.db import models class FooChoices(models.TextChoices): FOO = "foo" BAR = "bar" class FooModel(models.Model): type = models.CharField(max_length=50, choices=FooChoices.choices) @property def is_foo(self): # 写法一 return self.type == FooChoices.FOO # 写法二 return self.type is FooChoices.FOO
结论:推荐使用 == 进行比较
原因如下:
- 从数据库读取
CharField的值时,返回的是普通字符串类型,而FooChoices.FOO是一个枚举成员对象,二者身份完全不同。用is比较会直接返回False,导致逻辑错误。 - Django的
TextChoices重载了==运算符,会自动将枚举成员与对应实际值(即"foo")进行比较,因此和数据库返回的字符串比较能得到正确结果。
验证示例:
>>> FooChoices.FOO == "foo" True >>> FooChoices.FOO is "foo" False
所以正确写法是使用==来对比模型字段值与TextChoices成员。
内容的提问来源于stack exchange,提问作者LondonRob
相关产品推荐
相关产品推荐

