jayt
jayt

Reputation: 768

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

and

DEPT = (
        ('Production', 'Production'),
        ('Purchasing', 'Purchasing'),
        ('Support', 'Support')
    )

Either on a DB level or from a models perspective? Are there any advantages from writing it one way over another?

Upvotes: 0

Views: 80

Answers (4)

Zulu
Zulu

Reputation: 1

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.

Upvotes: 0

Alasdair
Alasdair

Reputation: 309089

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.

Upvotes: 0

Neeraj Kumar
Neeraj Kumar

Reputation: 3941

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

This is the good way that you can define choices.

Upvotes: 0

cosinepenguin
cosinepenguin

Reputation: 1575

Apart from the idea that you can change the variable at a later time in the first example (and might make your code cleaner), there is no difference between the two!

Upvotes: 1

Related Questions