简体   繁体   中英

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

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). 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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