【问题标题】:Inherit Django choice class to extend it?继承 Django 选择类来扩展它?
【发布时间】: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


    【解决方案1】:

    你需要从父母那里解压。您可以使用 星号 (*):

    class ExtendedChoices(UserChoices):
    
        OTHER_CHOICE = "other_choice"
    
        @classmethod
        def choices(cls):
            return (
                *UserChoices.choices(),  # ← an asterisk to unpack the tuple
                (cls.OTHER_CHOICE, _("Other choice")),
            )

    如果我们在另一个元组中解包一个元组,我们构造一个元组,其中包含解包元组的所有项作为新元组的元素。例如:

    >>> x = (1,4,2)
    >>> (x, 5)
    ((1, 4, 2), 5)
    >>> (*x, 5)
    (1, 4, 2, 5)
    

    如果我们因此不使用星号,它只会将x 视为一个元组,因此我们构造一个以元组x 作为第一个元素的二元组。

    如果我们解包第一个元组,我们会得到一个 4 元组,其中前三个元素来自 x,然后是 5

    【讨论】:

      猜你喜欢
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多