DEV Community

Priyanshu Panwar
Priyanshu Panwar

Posted on

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)
Enter fullscreen mode Exit fullscreen mode

Extracting all objects of a model

Let's extract all the students.

students = Student.objects.all()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Or there is another way to do this.

stud = Student.objects.get(pk=1)
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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 __.

stud_2006 = Student.objects.filter(reg_date__year=2006)
Enter fullscreen mode Exit fullscreen mode

This will return all the students registered in 2006.

stud_p = Student.objects.filter(name__startswith='P')
Enter fullscreen mode Exit fullscreen mode

This will return all the students whose names start with 'P'.

Using Q() - Very Powerful

This is used to add many filters in a single filter using | (or), & (and).

stud = Student.objects.filter(Q(name__startswith='P') | Q(reg_date__year=2006))
Enter fullscreen mode Exit fullscreen mode

This will return both the students whose names start with 'P' or who are registered in year 2006.

THANK YOU

Find me on Priyanshu Panwar | LinkedIn

Top comments (0)