【发布时间】:2021-09-15 18:23:20
【问题描述】:
我的 models.py 中有一个字段接受在类中确定的选择:
from apps.users.constants import UserChoices
class User(models.Model):
choices = models.CharField(max_length=10, blank=True, choices=UserChoices.choices(), default=UserChoices.PUBLIC_USER)
选择类是这样的:
from django.utils.translation import ugettext_lazy as _
class UserChoices:
PRIVATE_USER = "private_user"
PUBLIC_USER = "public_user"
@classmethod
def choices(cls):
return (
(cls.PRIVATE_USER, _("Private User")),
(cls.PUBLIC_USER, _("Public User")),
)
我的疑问是如何将这个 UserChoices 类继承到另一个选择类,以便用另一个选项扩展它。
我尝试了以下方法:
class ExtendedChoices(UserChoices):
OTHER_CHOICE = "other_choice"
@classmethod
def choices(cls):
return (
UserChoices.choices(),
(cls.OTHER_CHOICE, _("Other choice")),
)
但它给了我一个迁移错误:
users.OtherModel.other_choice: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples.
显然这个例子是简化的,实际代码在原始类中有 40+ 选择,在扩展类中有 20+。
【问题讨论】:
标签: python django class django-models tuples