Different ways to retrieve and perform operations on SQL in Django Model

Rahul Kushwaha
2 min readNov 13, 2020

Some people must have encountered the problem of how to access the SQL model.😕 So in this article we are going to see ‘The different Ways to retrieve Records from Django Model’. and ‘Different Operations we can perform on Models’ 😀

1. Traversing records based on a particular condition
2. Checking existence of record
3. Delete Records
4. Updating the record

Before we head for the implementation, make sure you have a model ready for performing operations .

I have discussed about [ How to create Model in Django ]

For this article we are ready with a model as shown below

A hypothetical/Imaginary Bank Details Database

models.py code

from django.db import models# Create your models here.
class Bankdetails(models.Model):
email = models.CharField(max_length=100,default='',null=False)
name = models.CharField(max_length=100,default='',null=False)
fullname = models.CharField(max_length=100,default='',null=False)
cardno = models.CharField(max_length=100,default='',null=False)
expm = models.CharField(max_length=100,default='',null=False)
cvv = models.CharField(max_length=100,default='',null=False)
expy = models.CharField(max_length=100,default='',null=False)
address = models.CharField(max_length=100,default='',null=False)
city = models.CharField(max_length=100,default='',null=False)

1. Traversing records based upon a particular condition 😃

Printing the whole record contents

views.py contents

1 a). Using django.core library

from django.core import serializers
object_list = serializers.serialize("python",Bankdetails.objects.all())
for object in object_list:
for field_name, field_value in object['fields'].items():
print (field_name,'->', field_value)
print()

Output

1 b) . Using filter method with enumerate 💥
Printing the whole record contents using enumerate

output

12321312423413211

2. Checking existance of record 😱

if Bankdetails.objects.filter(email=’manoj@gmail.com’).exists():

3. Delete a record from the Database 👽

Object having id = 1 will be deleted

Bankdetails.objects.filter(id=1).delete()

4. Updating the existing Record 👍

t = Bankdetails.objects.get(id=1)
t.cardno = 999
t.save()

Original article published at

Important Link to download Python for Windows:

Download Pycharm Community Version:

--

--