A beginners guide to Django Models
Objectives and Requirements
In this tutorial I'm going to introduce you to models in Django, we'll figure out how to make queries with a Django powered application we're building for a client who owns a warehouse.
In order to gain full understanding of this tutorial I'm going to assume you have some understanding of the following :
- Programming In Python
- Object Oriented Programming in python
- Basic Understanding of Databases
What are models in Django?
A model is a representation of a database table in the form of classes. Instances of your data ( records ) are represented as objects in python. In other words, each model is a python class that inherits or subclasses
django.db.models and each attribute of the model represents a database field.
from django.db import models class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
In the example above , the Author class represents a database table and the firstname and lastname class attributes of the Author class map to a column of our Author database. With this knowledge we can build out our warehouse management system.
To get started we need to setup our django project:
- Create A Virtual Environment with virtualenv
pip install virtualenv virtualenv env cd env .\Scripts\activate
- Install Django
pip install django cd..
- Start Your Project
django-admin startproject warehousesys cd warehousesys python manage.py runserver
- You should see the following on the comand line
Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. April 5, 2020 - 15:50:53 Django version 2.2, using settings 'warehousesys.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
We can go ahead and create our first app called stock, this app wil manage all products in the warehouse.
python manage.py startapp stock
This command should create a directory as follows
stock/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py
We need to tell django that we have a new app that it has to track. To do that add a dotted path to the stock app in the installed app section of our settings
Your settings app should look like this.
INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stock.apps.StockConfig', #new ]
Next run this command
python manage.py migrate
The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in our warehousesys/settings.py file and the database migrations shipped with the app.
In our models.py we'll create our first model called
product , go ahead and open
models.py and type in the following model.
from django.db import models class Product(models.Model): name = models.CharField(max_length=200) quantity = models.PositiveIntegerField(max_length=200) price = models.DecimalField(max_digits =10, decimal_places=2)
Congratulations you've successfully created your first model in Django 🎉.
But wait, we created our model but has it refelected in our databse , answer is no. As described earlier on , models are representations of our database tables so in order to make a table out of our product table, we have to explicitly tell django to use our created model as a template for creating our database table. Let's go ahead and do that .
Next we need to run this command
python manage.py makemigrations stock
You should see something like this
Migrations for 'stock': stock/migrations/0001_initial.py: - Create model Product - Add field name to Product - Add field quantity to Product - Add field price to Product
makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk. You can read the migration for your new model if you like; it’s the file
stock/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.
Django automatically creates an api on the fly that we can used to query our database.To invoke the Python shell, use this command:
python manage.py shell
Once you’re in the shell you can populate our databse.
#1. Import our model from our stock app from stock.models import Product # No products are in the system yet Question.objects.all() #<QuerySet > #Let's create our first product product_1 = Product(name="Red Hoodie", quantity=50, price=12.99) # save the object in the database product_1.save() product_1.id() # 1 product_1.name # Red Hoodie Question.objects.all() #<QuerySet [<Product: Product object (1)>]>
is not a nice way to return our product names for easy retrieval in our warehouse. To fix that we can use **str **() method in python to return the product name in a queryset
from django.db import models class Product(models.Model): name = models.CharField(max_length=200) quantity = models.PositiveIntegerField(max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name # we can add a custom method that tells # us if the product is high value or note def is_high_value(self): if self.price > 20: return True else: return False
Save these changes and start a new Python interactive shell by running python manage.py shell again:
from stock.models import Product # Make sure our __str__() addition worked. Product.objects.all() #<QuerySet [<Product: Red Hoodie>]> ## keyword arguments Product.objects.filter(id=1) #<QuerySet [<Product: Red Hoodie>]> p = Product.objects.filter(id=1) p.is_high_value() # False
And that's it, we successfully setup our django project and added a product to our warehouse stock.