【问题标题】:Adding a choice to a choice field if it is not there如果选项字段不存在,则向选项字段添加选项
【发布时间】:2014-07-15 04:06:56
【问题描述】:

您好,我目前有这个型号

class Member(models.Model,get_fields):
    first_name = models.CharField(max_length = 20)
    last_name = models.CharField(max_length = 20)

ROLE_CHOICES = (
    ('PLAYER', 'Player'),
    ('CONDUCTOR', 'Conductor'), 
    ('COMMITTEEMEMBER', 'Committee Member'),
    ('LIBRARIAN', 'Librarian'),
    ('TUTOR', 'Tutor'),
    ('ACCOUNTANT', 'Accountant'),
    ('PRESIDENT', 'President'),
    ('CHAIRMAN', 'Chairman'),
    ('SECRETARY', 'Secretary'),
    ('OTHER', 'Other')
)
role_choices = models.CharField(_('Role'), max_length = 20, choices = ROLE_CHOICES)

如果不可用,我希望用户能够添加额外的角色选择。所以我也创建了

class ExtraRole(models.Model,get_fields):
    name = models.CharField(max_length = 20)

如何设置表单以便用户能够在创建成员视图上创建一个额外角色(如果它不存在),然后将其添加到 role_choices 元组中?是否可以将外键添加到 role_choices 元组?这会是正确的做法吗?

【问题讨论】:

    标签: django forms model views


    【解决方案1】:

    可以将类似于外键的内容添加到 role_choices,但这会非常复杂,并且也是“错误”的做法。您应该为角色选择创建一个新模型。如果选择不会改变,使用元组作为您的选择很好,但如果您想让用户能够编辑这些选择,那么您需要将其创建为模型并向成员模型添加外键字段

    class MemberRole(models.Model):
        name = models.CharField(max_length=20)
    
    class Member(models.Model, get_fields):
        first_name = models.CharField(max_length = 20)
        last_name = models.CharField(max_length = 20)
        role_choices = models.ForeignKey(MemberRole)
    

    【讨论】:

    • I think what he wants is that when 'other' is selected, a text-box with 'please complete' will appear (or already be there but only complete it if 'other' is selected.) .
    • 即使在这种情况下,仍然需要新模型和外键,因为为选择创建一个“灵活”元组真的很糟糕。像这样的情况就是外键的用途。
    • 是的,我同意你的看法。但是ROLE_CHOICES需要保留。
    • 问题中没有提到
    • 感谢您的回答,对不起,我无法投票,因为我没有足够的代表,但我应该能够应付。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2018-07-02
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    相关资源
    最近更新 更多