Module-02 Models
Module-02 Models
Module-02
Models
Configuring Databases
Initial Configuration:
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.
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.
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.
2
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62
• Django models represent the "M" in the MTV (or MVC) pattern, standing for "Model."
• 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.
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:
• Storing models as Python code facilitates version control, making it easier to track changes
to data layouts.
• Django models offer higher-level data types (e.g., for email addresses, URLs) that SQL
may lack.
3
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62
Introduction:
• 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.
• 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
• In the models.py file of the Django app (created using the startapp command), the
following Python code is entered:
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
NULL,
);
• 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 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
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.
• 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.
p1.save()
p2.save()
7
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62
publisher_list = Publisher.objects.all()
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.
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
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.
• 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.
• 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
• 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:
p = Publisher(name='Apress',
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
• 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:
12
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62
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.
• 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.
Components of Publisher.objects.all():
• Publisher: Refers to the model for which data is being looked up.
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:
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')
FROM books_publisher
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")
Exceptions:
Example:
Publisher.objects.get(country="U.S.A.")
Example:
Publisher.objects.get(name="Penguin")
Exception Handling:
Example:
try:
p = Publisher.objects.get(name='Apress')
except Publisher.DoesNotExist:
else:
Exceptions Details:
15
FULL STACK DEVELOPMENT ISE-RNSIT 21CS62
class.
• Publisher.DoesNotExist and Publisher.MultipleObjectsReturned respectively.
• To delete a single object from the database, call the object’s delete() method.
Example:
p = Publisher.objects.get(name="O'Reilly")
p.delete()
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:
Example:
Publisher.objects.filter(country='USA').delete()
• This line deletes only the objects where the country is set to 'USA'.
Schema Evolution
• 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.
• 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.
• 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.
• 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.
• Learn about testing strategies for schema changes, including creating backups and running
migrations in a staging environment.
• 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