简体   繁体   中英

Django Model Choices difference

In Django, when creating choices, is there any difference between...

prod = 'Production'
purch = 'Purchasing'
support = 'Support'
DEPT = (
    (prod, 'Production'),
    (purch, 'Purchasing'),
    (support, 'Support')
)

除了可以在以后的第一个示例中更改变量(可能使代码更简洁)的想法之外,两者之间没有区别!

PROD, PURCH, SUPPORT = range(3)
DEPT = ( 
(PROD, 'Production'),
(PURCH, 'Purchasing'), 
(SUPPORT, 'Support')
 )

This is the good way that you can define choices.

There is no difference at the database level.

The first method means that you can refer to the variables later in your code, for example:

class Employee(models.Model):
    ...
    department = models.CharField(max_length=30, choices=DEPT, default=prod)

This is nicer that default=prod[0][0] , or default="Production" (there's a chance of a typo if you repeat the string rather than using the variable.

i use the second form when i need the same information (word or char) in the forms (frontend) and backend (database) for a field, the first form, i think, is to put a mask to differentiate the data that is in forms and the data entered in the database. if you want, see first the difference between null and blank options in the introduction of django, next, see choices field in the model reference in the same doc.

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