Django Models

Learn via video courses
Topics Covered

Django models simplify database interactions by representing tables and fields within the LocalLibrary website. Each model typically corresponds to a database table, streamlining SQL complexities like creating, updating, or deleting records. This article elucidates model definitions, declarations, and primary field types. Additionally, it offers insights into accessing model data efficiently.

Models in Django

Django applications use Python objects called Models to access and manage data. These Models define the internal structure of the storing data like field types and their maximum size, default values, label text for forms, etc. Models creation is independent of which database you are using. You can use any Database. You don't need to talk to the database directly. You only need to create your Model structure and other code, and Django will take care of the dirty work of talking with the database.

Example

first model

Creating Django Models

The above section of the article shows the benefits of having Django Models. Let's have a look at the creation of Django Models. When creating a Django Model, we have to choose field names that do not clash with the inbuilt keyword of the Django Model API, such as clean, save, or delete. Words, like delete or save are used as a command in Django. The basic Syntax for creating a Django Model is given below:

Syntax

To create a Model in Django, first, we have to navigate to the model.py file of a Django app, i.e., <app>/model.py then enter the following code.

Once we have written the above code in the app's model.py file of Django, we need to execute the following command to tell Django to create the actual table with this Field. First, we will create the SQL Command to create the table with the above fields with the help of the command:

Python manage.py make migrations

After execution of the above command, we have to run the following command to execute the SQL Query to create a Model as a Table is created

Python manage.py migrate

Now, we have created the above Model as a table in our database successfully.

Render a Model in Django Admin Interface

Once the Model is created, it is an important task for us to render that Model in Django admin Interface. If this is not done, the tables will not appear in the Django admin panel, and you will not be able to perform the CRUD (Create, Retrieve, Update, Delete)operation graphically. For displaying the Model in the Django admin interface, we need to modify app/admin.py.

We can verify whether the Model has been rendered in Django Admin. The Purpose of the Django Admin Interface is to be used to graphically implement CRUD (Create, Retrieve, Update, Delete). For that, first, we have to create a superuser with all the permission to perform the CRUD(Create, Retrieve, Update, Delete) operations. To create the superuser, the command will be :

After the superuser is created, one can log in to Django admin Dashboard with the URL localhost:8000/admin and use the credentials he provided during the superuser creation. Once you log in to the dashboard, you will see the Model you created in the above section of the article shown in the image below.

login

You can click on the Model name in the image's bottom left and perform the CRUD (Create, Retrieve, Update, Delete) operation.

crud

Django CRUD (Create, Retrieve, Update, Delete) Function-Based Views

Django is a web framework that allows you to easily construct web applications without the installation or dependency issues that other frameworks typically have. Django's design is built on MVT (Model View Template) and centers on CRUD (Create, Retrieve, Update, Delete) activities. CRUD is best described as a method for developing a Django web application. CRUD generally refers to executing Create, Retrieve, Update, and Delete actions on a database table. Let's talk about what CRUD truly implies.

crud property

Create - Create creates or adds new items to a database table. It is equivalent to post operpost-operationo.

Retrieve- Read, retrieve, search, or display existing items as a list (List View) or retrieve a specific entry in detail (Detail View). It is equivalent to getting an operation in Django.

Update - This is used to add to or change existing entries in a database table. It is equivalent to putting a put an operation in Django.

Delete - Delete, deactivate, or eliminate existing database entries from a table.

Fields

The fields of the Django Model defined within the Model class are the names of the mapped table's columns. The field names of models should not contaPython-reserved terms such as clean, save, or delete.

Field Types

Django provides various built-in field types.

Field NameClassParticular
AutoFieldclass AutoField(**options)This is an IntegerField that automatically increments the value.
BigAutoFieldclass BigAutoField(**options)This is a 64-bit integer, similar to an AutoField, except it is guaranteed to fit integers ranging from 1 to 9223372036854775807.
BigIntegerFieldclass BigIntegerField(**options)It is a 64-bit integer, similar to an IntegerField, but with the added benefit that it will always fit between -9223372036854775808 and 9223372036854775807.
BinaryFieldclass BinaryField(**options)This field is used to store raw binary data.
BooleanFieldclass BooleanField(**options)This is a Boolean field, and the default form widget for this field is a Checkbox as Input.
CharFieldclass CharField(max_length=None, **options)It string field, for small- to large-sized strings.For large amounts of text, use TextField.
DateFieldclass DateField(auto_now=False, auto_now_add=False, options)It is a date field, and in Python, a DateTime.date instance is used to represent it.
DateTimeFieldclass DateTimeField(auto_now=False, auto_now_add=False, **options)It is used to represent date and time in Python using a DateTime.DateTime example.
DecimalFieldclass DecimalField(max_digits=None, decimal_places=None, **options)This field is a fixed-precision decimal number represented by a Decimal object in Python.
DurationFieldclass DurationField(**options)periods of time can be stored in this field.
EmailFieldclass EmailField(max_length=254, **options)It is a CharField that determines if the value is an email address that is legitimate or not.
FileFieldclass FileField(upload_to=None, max_length=100, **options)This field is a file-upload field.
FloatFieldclass FloatField(**options)This field is a floating-point number represented in Python by a float instance in Django.
ImageFieldclass ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)This field checks that the uploaded object is a legitimate picture in addition to inheriting all of FileField's properties and functions.
IntegerFieldclass IntegerField(**options)It is an integer field. In all databases that Django supports, values between -2147483648 and 2147483647 are secure.
NullBooleanFieldclass NullBooleanField(**options)This field is Similar to a BooleanField, but with NULL as a possible value.
PositiveIntegerFieldclass PositiveIntegerField(**options)his field is like an IntegerField but must be either positive or zero (0).
SmallIntegerFieldclass SmallIntegerField(**options)This field is like an IntegerField, but only allows values under a certain (database-dependent) point.
TextFieldclass TextField(**options)This field contains a lot of text. A Textarea is the form widget by default for this field.
TimeFieldclass TimeField(auto_now=False, auto_now_add=False, **options)This field is used to represent time in Python by a DateTime.time instance

Field Options

Each Field in Django Model requires certain parameters for setting column properties. For example, to provide a varchar database, CharField requires mac length.

All fields in Django Model have common arguments. Everything is optional.

Field OptionsProperties
NullDjango Model will store empty values as NULL in the database.
BlankThis option is used to allowing the Field to be blank.
ChoicesIt is an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.
DefaultThis option is used to provide the default value for the field. It can be a value or a callable object.
help_textThis is used to display additional text with the form widget. It's useful for documentation even if your field isn't used on a form.
primary_keyThis field is used to create the primary key for the Model.
UniqueThis field must be unique throughout the table.

Automatic Primary Key Fields

Django assigns an auto-incrementing primary key to each Model by default, with the type provided by each app in AppConfig.default auto field or globally in the DEFAULT_AUTO_FIELD setting. For example: id = models.BigAutoField(primary_key=True) If you want to use a different primary key, set primary key=True on one of your Django model fields. Django will not add the automatic id column if it detects that you have manually defined a set Field.primary_key

Primary key=True is required for only one Field in each Django Model (either explicitly declared or automatically added).

Verbose Field Names

A verbose name is an optional argument given to any field. Each field type, except for ForeignKey, ManyToManyField, and OneToOneField, takes an optional first positional argument. If no verbose name is specified, Django will generate one using the Field's attribute name, converting underscores to spaces.

In this example, the verbose name is "name":

title = models.CharField("name", max_length=10)

In this example, the verbose name is "title":

title = models.CharField(max_length=30)

We have to use the verbose_name keyword as an argument in ForeignKey, OneToOneField, and ManyToManyField because they require the first argument to be a Model class. The initial letter of the verbose_name should never be capitalized. Django will use uppercase the first letter wherever it is required.

Model Attributes

In Django, the Manager is the most crucial feature of a model. Model Manager is the interface via which Django Models get database query operations and is used to obtain instances from the database. The default name is object if no custom Manager is set. We can only access Managers through Model classes, not Model instances.

Model Methods

Model Methods are techniques to use the Django Model in a more customized way according to your choice. This is a useful strategy for putting business logic in a single location. For example, if we want to display the description of an object, we can create a function inside the Model itself to send the customized length of the description.

Model Inheritance

Model inheritance in Django works roughly equivalent to standard class inheritance in Python. For Model inheritance, the base class must be a subclass of Django.DB.models.Model. The only thing you have to decide is whether you want the parent Models to be Models with their properties (with their database tables) or whether you want the parents to simply contain common information that will only be visible through the kid Models. There are mainly three types of inheritance in Django.

Abstract Base Classes

Abstract base classes are used for Model Inheritance when you just want to utilize the parent class for retaining information that you don't want to write out for each child Model.

Multi-Table Inheritance

When you want each Model to have its database table and are subclassing an existing Model (maybe something from a completely different application), the multi-table inheritance approach is utilized for Model inheritance.

Proxy Models

Use the Proxy Models technique for Model inheritance if you just wish to alter a Model's Python-level functionality and not its fields in any manner.

Conclusion

  • Django Models are a pre-installed feature of Django, which is used to create table and their fields by taking care of the fields constrained.
  • Django applications use Python objects called Models to access and manage data. These Models define the internal structure of the storing data.
  • The fields of the Django Model defined within the Model class are the names of the mapped table's columns.
  • There are mainly three types of inheritance in Django Abstract base classes, Multi-table inheritance, and Proxy Models.