Edoardo Marziali
One Eye Doll

One Eye Doll

Django models: a quick introduction

Edoardo Marziali's photo
Edoardo Marziali
·Aug 27, 2021·

2 min read

Django's ORM is fantastic. Its object oriented approach makes Database implementation an easier task for coders.

Its philosophy sounds like "Simple things easy and hard things possible."

But at a first approach, it may seem quite chaotic for a beginner. Have no fear, in this simple tutorial we will observe the basics of Django's ORM and how to work with it.

Our example model

Suppose you're building an ecommerce website. Surely you will have to face a "Product" database table. In Django, thanks to the ORM, this can be achieved directly from Python code.

Model creation

class Student(models.Model):  
    product_name = models.CharField(max_length=20,req)  
    product_id = models.CharField(max_length=128)  
    is_digital = models.BooleanField() 
    price = models.FloatField()

    def __str__(self):  
        return self.product_name

Let's examine the code.

  • product_name

It is the name of our product. A CharField is used because it represents a string, and i choose an arbitrary length of the string as 20.

  • product_id

The id of the product. For example, it can be an hash of the product name, or a random string. It doesn't matter.

  • is_digital

It checks if the product is digital or not. As the name suggests, a Boolean field can contain only True or False.

  • price

The price. It is a float value.

  • str function

This function will change the name displayed in Django admin panel in what the return value is.

This is how the model looks like. Declaring a model can't be simpler than how it is. Django ORM will save you a lot of time, once you understand it!

Now, to update your project, it is required to migrations. To do so, run these commands in your shell:

python manage.py makemigrations
python manage.py migrate

Now our model is ready! But we need to add products, so how we do it programmatically?

Adding an object to model

Now let's see how to add products through python code:

product=Product.objects.create(product_name='Chair',product_id='1234', is_digital= False, price=20.0 

As we can see, we can create a Product object through Product.objects.create() method, giving all required fields as parameter, and then we can add it to our database with the save function.

Search in model

You can search for a value through the filter method:



Now, you should know some of the basics interactions with the Django's ORM. If you read my post until here, please follow me to not miss other Django related content.

Share this