0% found this document useful (0 votes)
8 views

Django Models

The document discusses Django models and how to create, retrieve, update, and delete data from a SQLite database using models. It describes creating a Member model class to define the database table fields, migrating the model to create the database table, inserting sample member records using the Python shell, updating a record's firstname, and deleting a record from the Member table.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Django Models

The document discusses Django models and how to create, retrieve, update, and delete data from a SQLite database using models. It describes creating a Member model class to define the database table fields, migrating the model to create the database table, inserting sample member records using the Python shell, updating a record's firstname, and deleting a record from the Member table.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Django

Django Models
A Django model is a table in database. In Django data is created in objects called Models and is
actually tables in a database.
Create Table (Model)
To create a model, navigate to the models.py file in the folder /members/. Open it, and add
a Member table by creating a Member class, and describe the table fields in it as below
File: my_tennis_club/members/models.py:
from django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
The first field, firstname, is a Text field, and will contain the first name of the members. The
second field, lastname, is also a Text field, with the member's last name. Both firstname and
lastname are set up to have a maximum of 255 characters.
SQLite Database
When we created Django project, we get an empty SQLite database. It was created in the root
(my_tennis_club) folder, and has the filename db.sqlite3. By default, all Models created in the
Django project will be created as tables in this database.
Migrate
Now when we have described a Model in the models.py file, we must run a command to actually
create the table in the database.
Navigate to the /my_tennis_club/ folder and run this command:
py manage.py makemigrations members
Django creates a file describing the changes and stores file in the folder /migrations/
# Generated by Django 4.2.2 on 2023-07-06
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Member',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('firstname', models.CharField(max_length=255)),
('lastname', models.CharField(max_length=255)),

By K Raja Sekhar
SVECW
Django

],
),
]

Note that Django inserts an id field for tables, which is an auto increment number, this is the
default behavior of Django and can override it by describing own id field. The table is not
created yet, to create we have to run one more command. Run the migrate command:
py manage.py migrate
Django will create and execute an SQL statement, based on the content of the new file in the
folder /migrations/.
Hint: view the SQL statement that was executed from the migration above. run this command
with migration number:
py manage.py sqlmigrate members 0001
Insert Data to Add Records
The Members table created is empty. We will use Python interpreter to add some members to it.
To open a Python shell, Type this command:
py manage.py shell
It looks like “>>>”
To insert data first use the below command
>>> from members.models import Member
To see at the Member table:
>>> Member.objects.all()
This should give an empty QuerySet object, like this: <QuerySet []> if empty, if not the count
will be displayed like <QuerySet [4]>. A QuerySet is a collection of data from a database.
Add records to the table:
>>> member = Member(firstname='Raja Sekhar', lastname='K')
>>> member.save()
To see if the Member table got a member:
>>> Member.objects.all().values()
This should display the data from database.
Output: <QuerySet [{'id': 1, 'firstname': 'Raja Sekhar', 'lastname': 'K'}]>
Add Multiple Records
We can add multiple records by making a list of Member objects, and execute .save() on each
entry as below:
>>> member1 = Member(firstname='Rama Lakshmi', lastname='G')
>>> member2 = Member(firstname='Lalitha Sri', lastname='K')
>>> member3 = Member(firstname='Kiran Kartheek', lastname='K')
>>> memberList=[member1,member2,member3]
>>> for x in memberList:

By K Raja Sekhar
SVECW
Django

... x.save()
>>> Member.objects.all().values()
OutPut:
<QuerySet [{'id': 1, 'firstname': 'Raja Sekhar', 'lastname': 'K'},
{'id': 2, 'firstname': 'Rama Lakshmi', 'lastname': 'G'},
{'id': 3, 'firstname': 'Lalitha Sri', 'lastname': 'K'},
{'id': 4, 'firstname': 'Kiran Kartheek', 'lastname': 'K'}]>
Update Records
To update records that are already in the database, we first have to get the record we want to
update:
>>> from members.models import Member
>>> x = Member.objects.all()[3]
x will now represent the member at index 3, which is "Kiran Kartheek". Now we can update the
values of this record as below and save
>>> x.firstname='K kartheek'
>>> x.save()
In the above example ‘firstname’ is updated and saved using save command. Execute the
command to see if the Member table got updated:
>>> Member.objects.all().values()
Result will look like:
<QuerySet [{'id': 1, 'firstname': 'Raja Sekhar', 'lastname': 'K'},
{'id': 2, 'firstname': 'Rama Lakshmi', 'lastname': 'G'},
{'id': 3, 'firstname': 'Lalitha Sri', 'lastname': 'K'},
{'id': 4, 'firstname': 'K kartheek', 'lastname': 'K'}]>
Delete Records
To delete a record in a table, start by getting the record we want to delete:
>>> from members.models import Member
>>> x = Member.objects.all()[0]
x will now represent the member at index 0, which is "Raja Sekhar".
Now we can delete the record:
>>> x.delete()
The result will be:
(1, {'members.Member': 1}), it tells us how many items were deleted, and from which Model.
If we look at the Member Model, we can find that member is removed from the Model
>>> Member.objects.all().values()
<QuerySet [{'id': 2, 'firstname': 'Rama Lakshmi', 'lastname': 'G'},
{'id': 3, 'firstname': 'Lalitha Sri', 'lastname': 'K'},
{'id': 4, 'firstname': 'K kartheek', 'lastname': 'K'}]>

Hint: Django CRUD (Create, Retrieve, Update, Delete) Function or operations.

By K Raja Sekhar
SVECW

You might also like