model.choices django code example
Example 1: field.choices django
Will create a select box for this in the model form. Use can select from the
options.The first element in each tuple is the actual value to be set on the model,
and the second element is the human-readable name. For example:
YEAR_IN_SCHOOL_CHOICES = [
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
(GRADUATE, 'Graduate'),
]
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
Example 2: django models choices example
from django.db import models
class Author(models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
class Book(models.Model):
author = models.ForeignKey('books.Author', related_name='books', on_delete=models.CASCADE)
title = models.CharField(max_length=128)
status = models.CharField(
max_length=32,
choices=[],
)
def __str__(self):
return '{}: {}'.format(self.author, self.title)