Reader small image

You're reading from  Becoming an Enterprise Django Developer

Product typeBook
Published inJun 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781801073639
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Michael Dinder
Michael Dinder
author image
Michael Dinder

Michael Dinder works as a senior backend developer at Cart, Inc. Michael has helped to develop projects for large enterprises such as PayPal and other companies such as Corcoran Pacific Properties, and countless more either directly or indirectly. He has been programming for more than 15 years with a number of different languages and frameworks, with a focus on Python/Django for the past 5+ years.
Read more about Michael Dinder

Right arrow

Chapter 3: Models, Relations, and Inheritance

Models represent tables, also known as objects, within a database. Django provides a simple way to map objects to a project's underlying database(s). We will use this mapping system to work with other components of Django in later chapters of this book, such as a template, view, or form, to name a few. Anything that relies on accessing data from within a database will rely on the models that we create. If a project connects to an external database system or the project uses an API to interact with data, then there is no need to create any models in that situation.

In this chapter, we will cover the following:

  • Writing model classes to create database tables
  • Using standard field types and third-party field types
  • Configuring field validators
  • Linking tables through field relationships
  • Working with model meta classes and options
  • Using model methods and method decorators
  • Practicing extending models
  • ...

Technical requirements

To work with the code in this chapter, the following tools will need to be installed on your local machine:

  • Python version 3.9 – used as the underlying programming language for the project
  • Django version 4.0 – used as the backend framework of the project
  • pip package manager – used to manage third-party Python/Django packages

We will continue to work with the solution created in Chapter 2, Project Configuration. However, it is not necessary to use the Visual Studio IDE. The main project itself can be run using another IDE or independently using a terminal or command-line window from within the project root folder. This is where the manage.py file resides. Whatever editor or IDE you are using, a virtual environment will also be needed to work with the Django project. Instructions for how to create a project and virtual environment can be found in Chapter 2, Project Configuration. You will need a database to store the...

Preparing for this chapter

Start by creating a new app in your project called chapter_3 by following the steps discussed in Chapter 2, Project Configuration, under the subsection titled Creating a Django app. As discussed in that section, don't forget to change the value of the name = variable for your app class found in the /becoming_a_django_entdev/becoming_a_django_entdev/chapter_3/apps.py file to now point to the path where you installed your app. Be sure to also include this app in your INSTALLED_APPS variable found in the settings.py file as well.

Writing model classes

Each model in your project represents a table within your database. The fields that are created in those models all relate to columns within that table. Django provides a technique called Object-Relational Mapping (ORM) to map models to the underlying database(s) that are configured in the settings.py file of a project. The ORM technique is a process used to convert data between two systems of incompatible data types. This means that Django takes the headache out of working directly with Structured Query Language (SQL) to perform queries. The Django ORM irons out odd differences between the various database types when interpreting SQL, making it a universal tool for working with all data structures. Now, you and your developers can focus more on developing and less on the headaches involved. Django does not require the use of SQL as a standard writing practice. However, if you want or need to, Django does provide a way to use basic SQL when performing query operations...

Working with model field relationships

Django provides three relationship types for linking tables:

  • Manytoone
  • Manytomany
  • Onetoone

A many-to-one relationship is defined by using a ForeignKey field, and the other two relationship types are defined using the self-explanatory ManyToManyField and OneToOneField. These fields are named appropriately after the relationship type that they represent.

Next, we will discuss the key components of working with model field relationships.

Field arguments

The three field types, ForeignKey, ManyToManyField, and OneToOneField, all accept the standard default, blank, and verbose_name field arguments that other field types accept. The null argument will have no effect on a ManyToManyField and will only apply to the ForeignKey and OneToOneField types. Two of these field types—ForeignKey and OneToOneField—require at least two positional arguments, the first being...

Using the Meta subclass

Model metadata is an inner class of a model called Meta. It is not required and completely optional but it does make using Django much more useful when it is included in your models. Metadata provides all of the "other" information that is not defined in model field arguments. The settings that are defined inside this class are called meta options, and there are quite a lot to choose from. We will go over only some of the most commonly used options in the following sections and how they can be helpful. A complete breakdown of all of the options is available here: https://docs.djangoproject.com/en/4.0/ref/models/options/.

Meta options – verbose_name and verbose_name_plural

We can use the verbose_name and verbose_name_plural options to specify what human-readable text is used in areas of the Django admin site or if we look it up later in the code that we write. We will introduce the Django admin site in Chapter 6, Exploring the Django Admin...

Customizing models

Model methods are custom functions written within a model class that provide added functionality related to a single record within a table. They let us create our own business logic and format field data as we need to. Django provides us with several default methods and we can also write our own custom methods. Custom methods can combine fields and return data derived from those two or more fields. Decorators are sometimes used in combination with model methods to provide even more functionality.

Some methods can let us perform special operations when an object is saved and/or deleted at the database level. Other methods are used when queries are performed or when rendering an object within a template. We will discuss some of the methods that Django provides and then demonstrate their uses. For a complete breakdown of the full capabilities of using Django's model methods, visit their documentation, found here: https://docs.djangoproject.com/en/4.0/topics...

Extending models

Extending a model is a way to write a set of fields and methods that can be shared in many different classes. This is also known as inheritance, which is a fundamental principle of the Python language, letting us write code once and reuse it over and over again. It is also a way to reuse or modify a class provided by Django itself, such as the built-in User model, which is a very common model to extend.

Next, we will practice extending our practice model called engine2 and then extend the Django User model, turning it into the Seller model. This would make the Seller object related to a Vehicle and also act as a User, provided with permission-based roles and permission group capabilities.

Extending basic model classes

Extending regular model classes is pretty easy to do. Follow these steps to extend the engine2 practice class:

  1. In your /chapter_3/models.py file, in the class named engine2, keep the name field as is and then add a new field called vehicle_model...

Using the Django shell

The Django shell is a powerful tool to add to any toolbox. It will activate the Python interactive interpreter and uses the Django database abstraction API to let us connect directly to the database(s) configured in a project. With this, we can write Python and perform queries directly from a terminal or command-line window.

To activate the Django shell, follow these steps:

  1. Open your terminal or command-line window and navigate to the root of your project. Make sure your virtual environment has been activated and then execute the following command:
    (virtual_env) PS > python3 manage.py shell
  2. You should see it print out the following information about the InteractiveConsole that was launched:
    Python 3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>>
  3. Your console...

Performing queries

Performing queries using the Django shell will give us some insight into how queries work. In the following subsections, we will discuss some common methods that are used.

Model method – all()

The all() method returns all records found in the table for that model object. This method will return a QuerySet in the following format, representing all entries that it finds:

(virtual_env) PS > python3 manage.py shell
>>> from becoming_a_django_entdev.chapter_3.models import Engine, Seller, Vehicle, VehicleModel 
>>> VehicleModel.objects.all()
<QuerySet [<VehicleModel: Blazer LT>, <VehicleModel: Enclave Avenir>, <VehicleModel: Envision Avenir>]> 

The chapter_3 data fixture only provides three VehicleModel and that is why a collection of only three objects is returned to us. Your results may vary. One of the reasons why we created a __str__() method, as was done earlier in this chapter, in the subsection titled...

Writing model managers

We now know that when we want to apply logic that pertains to a single object within a table, we will look into writing a model method. An advanced Django concept can allow us to add logic that would relate to the entire table of objects instead. That would be written using a model manager instead of a model method. By default, Django automatically creates a model manager for every model that you write. That manager is called the objects manager, as in when we write a query statement such as MyModel.objects.all(). Since the objects manager is already created for us, there is technically no need for us to create a model manager at all. However, custom model managers can be used in a project to provide additional methods that the entire table uses. We will discuss a simple use of this concept that adds filters to a table. To learn more about how model managers can be used in more depth, visit the official Django documentation, found here: https://docs.djangoproject...

Summary

In this chapter, we learned that models are building blocks of everything else we build that accesses data in a database. They provide the containers where all of a project's data will exist as a data storage device for this application. We now have a toolbox with tools related to the structure of the tables, such as the columns that exist or rules/constraints that we apply to them. Other tools help us to link these tables together that build the relationships between those tables. We also know how to transform the data that we have to provide other data not kept in those tables, but rather derived from it. Some of the concepts add performance power by doing work in the background, indexing data, and reducing the time that it takes to look up information. Querying objects is also a complex subject and there is a lot of material regarding it; use the concepts in this chapter to help guide you through researching more advanced ways of querying data, to help with complex...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Becoming an Enterprise Django Developer
Published in: Jun 2022Publisher: PacktISBN-13: 9781801073639
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Michael Dinder

Michael Dinder works as a senior backend developer at Cart, Inc. Michael has helped to develop projects for large enterprises such as PayPal and other companies such as Corcoran Pacific Properties, and countless more either directly or indirectly. He has been programming for more than 15 years with a number of different languages and frameworks, with a focus on Python/Django for the past 5+ years.
Read more about Michael Dinder