简体   繁体   English

如何在Django中为分组选项设置默认值

[英]how to set the default value for grouped choices in django

If I have some grouped choices for a models.IntegerField, how can I set the default value to a combination of those choices 如果我对model.IntegerField有一些分组选择,如何将默认值设置为这些选择的组合

ex: 例如:

class ForumThread():
    STATE_CHOICES = (
        ('Sticky', (
            (True,  'True'),
            (False, 'False')    )     ),
        ('Blocked', (
            (False, 'False')
            (True,  'True')     )     ),
    )

    name = models.CharField(max_length= 256)
    description = models.CharField(max_length= 256)
    state = models.IntegerField(choices= STATE_CHOICES)

for this class I want to set the default for the 'state' field to Blocked -> False and Sticky -> False 对于此类,我想将“状态”字段的默认值设置为“阻止”->“假”和“粘滞”->“假”

Thanks 谢谢

You have misunderstood what grouped choices do. 您误解了分组选择的作用。 They are for presentation only - your IntegerField can only represent one single value, which in your case will be either 0 or 1 (for False or True). 它们仅用于表示-您的IntegerField只能表示一个值,在您的情况下为0或1(对于False或True)。 The only thing the groups do is provide headings within the select box. 这些组唯一要做的就是在选择框中提供标题。 There's no way in the setup you have to have separate values for Sticky and Blocked. 在设置中,您没有办法为“粘性”和“阻止”设置单独的值。

You need two integer fields - one for Sticky and one for Blocked. 您需要两个整数字段-一个用于“粘性”字段,一个用于“阻止”字段。

Then you can set the defaults in the usual way in the field itself. 然后,您可以使用常规方法在字段本身中设置默认值。

If you want the fields to be mutually exclusive, there are a number of ways you can approach this - modifying the save method is a good balance of ease and straightforwardness. 如果您希望字段互斥,则可以使用多种方法来实现此目的-修改save方法是轻松与直接之间的良好平衡。

http://docs.djangoproject.com/en/dev/ref/models/instances/#saving-objects http://docs.djangoproject.com/en/dev/ref/models/instances/#saving-objects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM