Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Django query for database operation

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

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

First Create 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(variable1=value,variable2=value)

 according to Student Model class

 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 row then delete 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 into Student Class

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

5)  Django query for data selection according to a column name

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

for Student Class
s = Student.objects.filter(colname=value)   #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 record using Order based on ascending and descending order?

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

to implement ModelClassname

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


Post a Comment

POST Answer of Questions and ASK to Doubt

Previous Post Next Post