Django query for database operation using Python Shell


Django provides a NoSQL query means it does not support SQL, We will write queries in Object patterns using Python script.

Now I am discussing queries in Django that can be used to implement database operations.

First Create a Model Class and define columns according to requirements.

class Student(models.Model):
   rno = Model.CharField(max_length=50)
  sname = Model.CharField(max_length=50)


python makemigrations appname 
python migrate

If you want to run the query using Python Shell then first use the following command?

python shell

1)  Django query for data insertion:-

   ref =  ModelClass(fieldname1=value,fieldname2=value)

for the Student Model class, the insert query would be.

 obj = Student(rno='1001',sname='xyz')

2)  Django query for data updation:

for updation, we will perform two operations first find the row  then update the row

 ref = ModelClassName.objects.get(pk=value)  # find row to update
 ref.columnname = value

Example for Student Model Class:-

s =  Student.objects.get(pk=value)

3)  Django query for data deletion:-

    for deletion, we will perform two operations first find the row then delete the row

    ref = ModelClassname.objects.get(pk=value)

   for Student Class, this Query will be implemented this way:-

    s = Student.objects.get(pk=value)      #  display data in Object

4)  Django query for data selection:-
ref = ModelClassName.objects.all()    #for Selection

Example of Student Class

s = Student.objects.all()   # display data in QuerySet

5)  Django query to select record based on condition

ref = ModelClassName.objects.filter(columnname=value)

for Student Class

s = Student.objects.filter(rno=1001)   #display Data in QuerySet

6) Django Query to find a record based on pattern matching similar to LIKE Operator of SQL:-

ref = ModelClassName.objects.filter(colunname__startsWith='char')

for Student Class

obj = Student.objects.filter(sname__startsWith='s')

7) Django Query to find a record based on pattern matching similar to LIKE Operator of SQL:-

ref = ModelClassName.objects.filter(colunname__endsWith='char')

for Student Class

obj = Student.objects.filter(sname__endsWith='s')

8) Django Query to display records using Order based on ascending and descending order?

ref = ModelClassName.objects.order_by('-columnname')[:2]

to implement Student Model

obj = Student.objects.order_by('-fees')[:2]


Post a Comment


POST Answer of Questions and ASK to Doubt

Post a Comment (0)