Django models

Django uses models to structure and organize the data of a web application. Typically written as a class in Python inheriting from the django.db.models.Model class, a model supports object-oriented thinking in a web development project, containing attributes and class methods that are used to store and process data for the given website.

For example, the following code is for a Django model, implementing the same Person class that we considered in the previous chapter:

from django.db import models

class Person(models.Model):
name = models.CharField(max_length=30)

def say_hi(self):
return f"Hello, I'm {self.name}."

Additionally, each model corresponds to a database table in the backend of a Django project, and Django handles the creation of any database table automatically. Still looking at the preceding class model, the equivalent of the following SQL code will be executed by Django:

create table myapp_person (
"id" serial not null primary key,
"name" varchar(30) not null
);

Additionally, Django can specify relationships between different tables, commonly used in database management. Specifically, the following are used:

  • django.db.models.ForeignKey can be used instead of a regular Field type to indicate a many-to-one relationship in the class model declaration.
  • django.db.models.ManyToManyField can be used instead of a regular Field type to indicate a many-to-many relationship in the class model declaration.
  • The same goes for django.db.models.OneToOneField and a one-to-one relationship.

All in all, the Django Pythonic model design makes it as easy as possible for Python developers to get into the field of web development, while still ensuring the correctness and robustness of the project structure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.105.108