In this first article about Django-orm, I will discuss how to retrieve model objects using Django-orm.
Create a Django model.
from django.db import models
class Player(models.Model):
name=models.CharField(max_length=50)
team=models.CharField(max_length=50)
nation=models.CharField(max_length=50)
-
After creating a Django model Player in models.py file, run
python manage.py makemigrations
this command will generate a migration file in the migrations folder. Then, runpython manage.py migrate
this command will create a table with fields name, team and nation in the database. -
To interact with a Django application through a shell, run the command
python manage.py shell
To retrieve every entity in the Player table.
from app_name.models import Player
players = Player.objects.all() # this method returns queryset
- Here
objects
is a model manager which acts as a interface to the database.
To retrieve entity using the primary key.
from app_name.models import Player
players = Player.objects.get(pk=2) # this method returns object
-
ObjectDoesNotExist
exception is raised if no entity found. -
To avoid raising an exception, use the filter method.
from app_name.models import Player
players = Player.objects.filter(pk=2).first() # this method returns None if no entity found