This website collects cookies to deliver better user experience
Playing with Django Model Objects - CheatSheet
Playing with Django Model Objects - CheatSheet
One must know how to play with Django models in their views in order to create efficient and short functions.
Let's take a model for example.
class Teacher(models.Model):
name = models.CharField(max_length=100)
class Student(models.Model):
name = models.CharField(max_length=100)
roll = models.CharField(max_length=100)
mentor = models.ForeignKey(Teacher, on_delete=models.CASCADE)
reg_date = models.DateTimeField(auto_add_now=True)
Extracting all objects of a model
Let's extract all the students.
students = Student.objects.all()
Extracting a student by ID
ID is the primary key in every model.
from django.shortcuts import get_object_or_404
def my_view(request):
obj = get_object_or_404(MyModel, pk=1)
Or there is another way to do this.
stud = Student.objects.get(pk=1)
The last one returns a error in case a student doesn't exist with the following id.
Filtering the objects
Simple filtering can be done with equating like
studs = Student.objects.filter(name='Ram Kapoor')
This will return the list of students whose name is Ram Kapoor.
We can also refer to the details of an attribute with the symbol __.