Now inside our new store app, open the models.py file/module. This file is already importing the models module from the django.db package.
Then you go ahead and create your first model class. You define the class, and this class inherits the model class in DJango.
Go ahead and specify the fields that your model will need. For instance, every product needs a title. So you will create a variable called title under your product class, and go ahead to specify the field type and field options. Field type can be charField, and field option can be “null” for instance. The charField in this case, takes an extra argument called “max_length” which specifies the maximum amount of characters needed in the field.
A product will also need a description, a description is quite long, so instead of a charField, we can use a textField(). The textField doesnt take any extra arguments.
class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True)Using the above info and code as reference, you can create the Customer class with its fields.
class Customer(models.Model): 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)Choice Fields
Lets say there are fields that you want the user to make a choice, or choose from a list of options, we use the choice fields. In django, we create a choice field by creating the field, and specifying the choices. The choices is usually an array of tuples. See below
class Order(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F'
PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed'), ] placed_at = models.DateTimeField(auto_now_add=True) payment_status = models.CharField(max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING)In the above code, we have used the PAYMENT_STATUS_CHOICES array to represent the choices. So when creating the payment_status field, we pass the choices argument in the charField, and set it to PAYMENT_STATUS_CHOICES. And we want it’s default value to be “PAYMENT_STATUS_PENDING”. We have set the max_length to 1 because we want to store just one character in our db. While the full word is displayed to the user for readability. So the “Pending, Complete and Failed” is what the user will see as choices, while its corresponding letters will be stored inside our db.