Skip to content
thesarfo

Note

Customizing the Database Schema

Adding indexes and a custom table name to a model via its Meta subclass.

views 0

Sometimes we need more control of our database schema, such as adding an index to a column, or doing some form of changes. How do we do that

Navigate to the Customer Class, and define metadata. This is where you define metadata about the model. So create a subclass called Meta inside the Customer class. And then define the metadata. Look up Django Meta Data for more info. See below.

class Customer(models.Model):
#all part of choice fields
MEMBERSHIP_BRONZE = 'B'
MEMBERSHIP_SILVER = 'S'
MEMBERSHIP_GOLD= 'G'
MEMBERSHIP_CHOICES = [
(MEMBERSHIP_BRONZE, 'Bronze'),
(MEMBERSHIP_SILVER, 'Silver'),
(MEMBERSHIP_GOLD, 'Gold'),
]
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField(unique=True)
phone = models.IntegerField()
birth_date = models.DateField(null=True)
# read about choice fields in django
membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE)
# look up django model metadata
class Meta:
db_table = 'store_customers'
indexes = [
models.Index(fields=['last_name', 'first_name'])
]