DEV Community

Cover image for Django models: Creating a simple model with records - [CREATE]
Arno Pretorius
Arno Pretorius

Posted on

Django models: Creating a simple model with records - [CREATE]

What are Django models?

A Django model is a built-in feature that is used to create tables and fields. These tables and fields are used to represent data that can be managed and accessed with Django. Simply put, models define the structure of the data that is stored.

Let's get started.

So, let's say that we want to keep track of data that is associated with different kinds of cars.

In this case, our model would be Car.


1) Creating a simple model in Django

Image description

The code below shows how we would create our model Car and the table structure for it:

# - models.py

from django.db import models

class Car(models.Model):
   type = models.CharField(max_length=30)
   colour = models.CharField(max_length=30)

Enter fullscreen mode Exit fullscreen mode

First of all, we navigate to our models.py file in Django and import models.

We then create our model, which is also known as a class. Since our model is Car, it would be appropriate to name it that.

We then create our fields, we have two of them, namely type and colour. The id field is generated by default when we create our model.

Next, it's important to decide in what form the data for our fields will be stored. Since we are just simply storing strings we can use CharField and set a max_length of 30 characters.

Once we have completed our model it is important that we migrate and push our changes.

To do so, we perform the following commands:

python manage.py makemigrations
Enter fullscreen mode Exit fullscreen mode
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

DONE! - Your model has been migrated and created!


2) Creating records for our table

Image description

The next step involves adding records to our tables by invoking the create() function, which helps us to populate the table from above.

Car.objects.create(type='ferrari', colour='red')

Car.objects.create(type='ford', colour='blue')

Car.objects.create(type='nissan', colour='black')

Car.objects.create(type='toyota', colour='white')
Enter fullscreen mode Exit fullscreen mode

DONE! - We have created records for our Model - Car


A final note…
For those that are interested in learning Django from scratch, feel free to check out my latest course:

Python Django: Ultimate Beginners Course - 2022

Top comments (0)