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)
command
python manage.py makemigrations appname
python manage.py migrate
If you want to run the query using Python Shell then first use the following command?
python manage.py shell
1) Django query for data insertion:-
ref = ModelClass(variable1=value,variable2=value)
ref.save()
according to Student Model class
obj = Student(rno='1001',sname='xyz')
obj.save()
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
...
ref.save()
Example for Student Model Class:-
Example for Student Model Class:-
s = Student.objects.get(pk=value)
s.rno=newvalue
s.sname=newvalue
s.save()
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)
ref.delete()
for Student Class, this Query will be implemented this way:-
s = Student.objects.get(pk=value) # display data in Object
s.delete()
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
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