如何为django模型的MultiSelectField设置默认值

时间:2018-01-21 13:08:44

标签: django django-models

from django.db import models

from multiselectfield import MultiSelectField

class Shop(models.Model):

DAYS = (
    ('sunday', 'Sunday'),
    ('monday', 'Monday'),
    ('tuesday', 'Tuesday'),
    ('wednesday', 'Wednesday'),
    ('thursday', 'Thursday'),
    ('friday', 'Friday'),
    ('saturday', 'Saturday'),
    ('Not any day', 'None'),
       )

closingDay = MultiSelectField(choices=DAYS)

click here to get picture 注意:当我把(默认= DAYS [7] [7])放在closingDay中。它的表现 元组索引超出限制。

2 个答案:

答案 0 :(得分:1)

当您指定默认= DAYS [7] [7] 时,您正在指定第8行的第8列的值,这显然不存在。 你应该分配 默认= DAYS [7] [0]

答案 1 :(得分:0)

实际上很容易,MultiSelectField 接受字符串数组或单个字符串作为 default

本示例中的一些有效值是。

#Using choice value
closingDay = MultiSelectField(choices=DAYS, default=DAYS[7][0])
#Multiple value default
closingDay = MultiSelectField(choices=DAYS, default=['sunday', 'tuesday', 'wednesday', 'thursday'])
#Direct String
closingDay = MultiSelectField(choices=DAYS, default='thursday')