0% found this document useful (0 votes)
14 views18 pages

Module-02 Models

Django

Uploaded by

dmprashanth6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views18 pages

Module-02 Models

Django

Uploaded by

dmprashanth6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

Module-02

Models
Configuring Databases

Initial Configuration:

• Django requires configuration to connect to the database server.


• Configuration settings are stored in the settings.py file.

Database Settings:

• DATABASE_ENGINE: Specifies the database engine to use. Must be set to one of the
available options (e.g., PostgreSQL, MySQL, SQLite).
• DATABASE_NAME: Specifies the name of the database. For SQLite, specify the full
filesystem path.
• DATABASE_USER: Specifies the username to use for database access.
• DATABASE_PASSWORD: Specifies the password for database access.
• DATABASE_HOST: Specifies the host for the database server. If using SQLite or the
database is on the same computer, leave this blank.
• DATABASE_PORT: Specifies the port for the database server.

Table: - Database Engine Settings

1
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

Testing Configuration:

• After configuring the database settings, it's recommended to test the configuration.
•Use the Django shell (python manage.py shell) to test the connection.
• Import connection from django.db and create a cursor.

• If no errors occur, the database configuration is correct.

Common Errors and Solutions: Errors may occur if settings are incorrect or if required
database adapters are missing.

Solutions include setting correct values for settings, installing required adapters, and
ensuring database existence and user permissions.

Table: - Database Configuration Error Messages

2
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

Defining and Implementing Models

Introduction to Django Models:

• Django models represent the "M" in the MTV (or MVC) pattern, standing for "Model."

•They describe the data in the database using Python code.

Purpose of Django Models:

• Models serve as the equivalent of SQL CREATE TABLE statements but in Python.
•Django executes SQL code behind the scenes based on these models. Models return
Python data structures representing rows in database tables. They also represent
higher-level concepts that SQL alone may not handle effectively.

Reasons for Using Python Models:

Introspection Overhead:

• Introspecting the database at runtime incurs overhead, especially for each request or server
initialization.
• Django opts for explicit Python model definitions to reduce this overhead.

Maintaining Context:

• Writing code in Python helps maintain a consistent programming environment, reducing


context switches.

Version Control and Ease of Tracking Changes:

• Storing models as Python code facilitates version control, making it easier to track changes
to data layouts.

Support for Higher-Level Data Types:

• Django models offer higher-level data types (e.g., for email addresses, URLs) that SQL
may lack.

3
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

• Consistency Across Database Platforms:


• Distributing a Python module describing data layouts is more pragmatic than separate sets
of SQL statements for different databases.

Drawback and Handling Strategies:

• Possibility of Code-Database Sync Issues:


• Changes to Django models may require corresponding changes in the database to maintain
consistency.
• Strategies for handling such issues will be discussed later in the chapter.

Utility for Generating Models:

• Django provides a utility to generate models by introspecting an existing database. •


This is particularly useful for quickly integrating legacy data into Django projects.

Your First Model

Introduction:

• This section presents an example of defining Django models for a basic


book/author/publisher data layout.

Justification for Example:

• The example focuses on these entities due to their well-known conceptual relationships.

• Books, authors, and publishers form a common data layout used in introductory SQL
textbooks.

Concepts, Fields, and Relationships:

• An author entity comprises fields for first name, last name, and email address. • A publisher
entity includes fields for name, street address, city, state/province, country, and website.
• A book entity contains fields for title, publication date, and relationships with authors and a
single publisher.

4
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

Translation to Python Code:

• In the models.py file of the Django app (created using the startapp command), the
following Python code is entered:

from django.db import models

class Publisher(models.Model):

name = models.CharField(max_length=30)

address = models.CharField(max_length=50)

city = models.CharField(max_length=60)

state_province = models.CharField(max_length=30)

country = models.CharField(max_length=50)

website = models.URLField()

class Author(models.Model):

first_name = models.CharField(max_length=30)

last_name = models.CharField(max_length=40)

email = models.EmailField()

class Book(models.Model):

title = models.CharField(max_length=100)

authors = models.ManyToManyField(Author)

publisher = models.ForeignKey(Publisher)

publication_date = models.DateField()

5
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

CREATE TABLE "books_publisher" (

"id" serial NOT NULL PRIMARY KEY,


"name" varchar(30) NOT NULL,

"address" varchar(50) NOT NULL,

"city" varchar(60) NOT NULL,

"state_province" varchar(30) NOT

NULL, "country" varchar(50) NOT

NULL,

"website" varchar(200) NOT NULL

);

Explanation of SQL Statement:

• The provided SQL statement creates a table named "books_publisher".

• It defines several columns including id, name, address, city, state_province, country, and
website.
• The id column serves as the primary key with the serial data type, ensuring unique
identifiers for each record.
• Other columns such as name, address, etc., have specified data types (varchar) and length
constraints.

Django's Automatic Generation:

• Django can automatically generate the above SQL CREATE TABLE statement based on
the model definitions.
• This automation simplifies the process of creating and managing database tables, reducing
the manual effort required.

6
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

Python manage.py makemigrations appname


Python manage.py sqlmigrate appname
Python manage.py migrate

Many-to-Many Relationships:

• In the case of many-to-many relationships, such as the authors field in the Book model,
Django creates an additional table (a "join table").
• This join table facilitates the mapping of books to authors without directly adding an
author's column to the Book table.

Primary Key Handling:

• Django automatically assigns a primary key to each model if not explicitly defined.

• The default primary key is an auto incrementing integer field named id.

• Django ensures that each model has a single-column primary key, which is a requirement
for data integrity.

Basic Data Access

# Importing the Publisher model class

from books.models import Publisher

# Creating Publisher objects and saving them to the database

p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', city='Berkeley',


state_province='CA', country='U.S.A.', website='http://www.apress.com/')

p1.save()

p2 = Publisher(name="O'Reilly", address='10 Fawcett St.', city='Cambridge',


state_province='MA', country='U.S.A.', website='http://www.oreilly.com/')

p2.save()

# Retrieving all Publisher objects from the database

7
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

publisher_list = Publisher.objects.all()

# Printing the list of Publisher objects

print(publisher_list)

Explanation:

• The provided Python code demonstrates basic data access using Django's high-level Python
API.
• Publisher.objects.all() fetches all the Publisher objects from the database.
• The objects are retrieved as a queryset, which is a collection of database objects of a
particular model.
• The print(publisher_list) statement displays the list of Publisher objects retrieved from the
database. However, the output may appear as [<Publisher: Publisher object>, <Publisher:
Publisher object>], as shown in the example, because Django doesn't automatically
provide a human-readable representation of objects. To display meaningful information,
you can define a __str__() method in the Publisher model class.

Adding Model String Representations

1. Purpose of Model String Representations:


• Model string representations are used to provide a human-readable representation of
objects when they are printed or displayed.

2. Implementing Model String Representations:


from django.db import models

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
8
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

country = models.CharField(max_length=50)
website = models.URLField()
def __str__(self):

return self.name

class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()

def __str__(self):
return f"{self.first_name} {self.last_name}"

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
publication_date = models.DateField()

def __str__(self):
return self.title

3. Explanation of __str__() method:


• The __str__() method serves the same purpose as __unicode__() but is used in
Python 3 and newer versions of Django.
• It returns a string representation of the object.

4. Usage and Effect:


• After implementing the __str__() method in the models, objects of these models
will display meaningful information when printed or converted to strings.

9
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

• The __str__() method for Publisher returns the name of the publisher, for Author it
concatenates the first and last name, and for Book it returns the title.

5. Updating the shell session:

• To see the changes take effect, exit the Python shell and start it again using python
manage.py shell.

• Now, when you retrieve objects from the database and print them, they will display
the custom string representation defined by the __str__() method.

6. Importance of __str__():

• Ensure that every model you define has a __str__() method to provide a meaningful
string representation of objects.
• Django uses this method's output in various situations where it needs to display
objects, enhancing usability and readability.

Definition of Unicode Objects:

• Unicode objects in Python are strings that can handle a wide range of characters,
including accented Latin characters, non-Latin characters, curly quotes, and
obscure symbols.
• They can represent over a million different types of characters.

2. Encoding Comparison:

• Normal Python strings are encoded, meaning they use encodings like ASCII, ISO
8859-1, or UTF-8.
• Handling fancy characters in normal strings requires tracking the encoding, or
else the characters might appear incorrectly when displayed.
• Mixing different encodings can lead to encoding problems, such as displaying
"???" or other odd characters.

10
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

3. Characteristics of Unicode Objects:

• Unicode objects do not have encoding; they use a consistent set of characters
known as Unicode.
• Working with Unicode objects in Python allows safe mixing and matching
without worrying about encoding issues.
• The __unicode__() method exemplifies how models in Django can have
additional behavior beyond representing database tables.
• It's a demonstration of how models can describe functionality that objects know
how to perform.

Inserting/Updating data
Inserting Data:

• To insert a row into the database using Django models, create an instance of the
model class with keyword arguments representing the field values.
• Instantiating the model class does not immediately affect the database.
• Data is inserted into the database by calling the save() method on the model
instance.

Example:

• Example of inserting data:

p = Publisher(name='Apress',

address='2855 Telegraph Ave.',

city='Berkeley',

state_province='CA',

country='U.S.A.',

website='http://www.apress.com/')

p.save()

Equivalent SQL:
11
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

• The SQL equivalent of inserting data

INSERT INTO books_publisher


(name, address, city, state_province, country, website)
VALUES
('Apress', '2855 Telegraph Ave.', 'Berkeley', 'CA', 'U.S.A.',
'http://www.apress.com/');

Primary Key Handling:

• When saving a new record, Django calculates and sets the primary key value for
the record.
• Subsequent calls to save() update the existing record in the database instead of
creating a new one.

Updating Data:

• To update data, modify the fields of the model instance and then call save() again.

• All fields are updated, not just the ones that have been changed, which may lead to race
conditions in some scenarios.

Example of Update:

• Example of updating data

p.name = 'Apress Publishing'


p.save()

Equivalent SQL for Update:

• The SQL equivalent of updating data

UPDATE books_publisher SET


name = 'Apress Publishing',

12
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

address = '2855 Telegraph Ave.',


city = 'Berkeley',
state_province = 'CA',
country = 'U.S.A.',
website = 'http://www.apress.com'
WHERE id = 52;

Considerations:

• Depending on the application, updating all fields may cause race conditions.

• Strategies for updating multiple objects in one statement are available, which can be more
efficient in certain scenarios.

Selecting and deleting objects


Selecting Objects:

• In web applications, querying existing database records is often more common than
creating new ones.
• The process of retrieving all records for a given model in Django.

Publisher.objects.all ()

Equivalent SQL:

• The Django code above roughly translates to the following SQL query.

SELECT id, name, address, city, state_province, country, website


FROM books_publisher;

Components of Publisher.objects.all():

• Publisher: Refers to the model for which data is being looked up.

• objects: Represents a manager, which handles table-level operations on data, including


data lookup. Every model automatically gets an objects manager.

13
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

• all(): A method on the objects manager that returns all rows in the associated database
table. It returns a QuerySet object.

QuerySets:

• QuerySets represent a specific set of rows from the database.


• Although QuerySets resemble lists, they are objects with additional functionalities. •
QuerySets are covered in detail in Appendix C.

General Pattern:

• Any database lookup in Django follows the pattern of calling methods on the manager
attached to the model being queried.

Filtering Data:

• It's common to need a subset of data from the database rather than retrieving everything
at once.
• Django's API allows filtering of data using the filter () method.

Usage:

• The filter () method takes keyword arguments, which are translated into SQL
WHERE clauses.

Example:

Publisher.objects. filter(name='Apress')

This translates to:

SELECT id, name, address, city, state_province, country, website

FROM books_publisher

WHERE name = 'Apress';

Using get() Method: • The get() method retrieves a single object from the database that matches
the specified criteria.

14
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

Example:

Publisher.objects.get(name="Apress")

• This returns a single object instead of a QuerySet.

Exceptions:

• If the query results in multiple objects, a MultipleObjectsReturned exception is raised.

Example:

Publisher.objects.get(country="U.S.A.")

• If no object matches the query criteria, a DoesNotExist exception is raised.

Example:

Publisher.objects.get(name="Penguin")

Exception Handling:

It's important to handle these exceptions in your code to prevent crashes.

Example:

try:

p = Publisher.objects.get(name='Apress')

except Publisher.DoesNotExist:

print("Apress isn't in the database yet.")

else:

print("Apress is in the database.")

Exceptions Details:

• DoesNotExist and MultipleObjectsReturned exceptions are attributes of the model's

15
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

class.
• Publisher.DoesNotExist and Publisher.MultipleObjectsReturned respectively.

Deleting Single Object:

• To delete a single object from the database, call the object’s delete() method.

Example:

p = Publisher.objects.get(name="O'Reilly")

p.delete()

• After deletion, the object is removed from the database.

Bulk Deletion:

• Objects can also be deleted in bulk by calling delete() on the result of any QuerySet.

Example:

Publisher.objects.filter(country='USA').delete()

Publisher.objects.all().delete()

• The first line deletes all objects with the country set to 'USA', while the second line deletes
all objects from the Publisher table.

Precautions:

• Django requires explicit use of all() if you want to delete everything in a table to prevent
accidental deletion of all data.

Example:

Publisher.objects.all().delete()

• Deleting all data from a table without using all() will result in an AttributeError.

Subset Deletion:

• If you're deleting a subset of data, you don't need to include all().


16
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

Example:

Publisher.objects.filter(country='USA').delete()

• This line deletes only the objects where the country is set to 'USA'.

Schema Evolution

Understanding Database Schemas:

• Understand the concept of a database schema and how it represents the structure of a
database.
• Learn about tables, columns, data types, primary keys, and foreign keys.

Django Models and Database Migrations:

• Understand how Django models map to database tables and how model fields correspond to
table columns.
• Learn about Django's migration system and how it helps manage schema changes over
time.

Adding New Fields:

• Learn how to add new fields to an existing model and create migrations for the same.

• Understand the concept of default values and how to handle existing data when adding new
fields.

Modifying Existing Fields:

• Learn how to modify the properties of existing fields (e.g., changing field types, max
lengths, etc.).
• Understand the implications of modifying fields and how to handle existing data during
field modifications.

Removing Fields: • Learn how to remove fields from a model and create migrations for the

17
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62

same.

• Understand the implications of removing fields and how to handle data loss or data
preservation.

Renaming Fields:

• Learn the process of renaming fields in Django, as it doesn't provide a direct way to do so. •
Understand the concept of creating a new field, migrating data, and removing the old field.

Data Migrations:

• Learn about Django's RunPython operation in migrations, which allows executing custom
Python code during schema changes.

• Understand how to use data migrations to handle complex data transformations or custom
logic during schema evolution.

Testing and Deployment:

• Learn about testing strategies for schema changes, including creating backups and running
migrations in a staging environment.

• Understand the importance of thoroughly testing migrations before applying them to a


production database.

Schema Evolution Best Practices:

• Learn about best practices for schema evolution, such as incremental changes, documenting
changes, and maintaining backward compatibility.
• Understand the importance of version control and collaboration when managing schema
changes in a team environment.

18

You might also like