Understanding Django Models

A model is a class that represents table or collection in our DB. The first thing to notice is that each model is represented by a Python class that is a subclass of django.db.models.Model. The parent class, Model, contains all the machinery necessary to make these objects capable of interacting with a database—and that leaves our models responsible solely for defining their fields, in a nice and compact syntax. - Models are defined in the `app/models.py` - Every model inherits from `django.db.models.Model`. - Each model class maps to a single table in the database. - Each model has fields, meta and methods. ## Structure Model classes are like database tables and model fields are like table columns. It is a mandatory part of a model. - `AutoField`: This is an auto-generated field. It's like an inbuilt primary key of the table. If any of the fields in a model class is not set as a primary key, then Django creates this field. - `CharField`: You have used this field in your model. It is like the char attribute of a database table. It can store text. For large texts, you can use TextField. - `TextField` - `BooleanField`: It is a True/False field. Example: `statement = models.BooleanField()` - `DateField`: This stores the date as an instance of the datetime.date class. Example: - `DateTimeField`: This stores the date-time stamp as an instance of the datetime.datetime class. - `DecimalField`: It is used to save data that has fixed decimal values like the price of any commodity (Rs. 10.99) - `IntegerField`: It stores integers. The range is -2147483648 to 2147483647. - `SlugField`: This a very handy field generally used to identify objects stored in the database. It is similar to CharField. To implement this, you need to have a field in your model which can be used as a string containing hyphens, letters, numbers, etc. similar to an URL. ## Field options - `blank`: If this parameter is set to True, then the field can be blank. If it is set to False, the field cannot be blank. - `null`: If this parameter is set to True, then the empty values will be stored as null in the database. If it's set to False, the field cannot be null. The default value is False. - `unique`: If this argument is True, Django runs a validation through the table and checks whether the value of the field is unique or not. - `choices`: You have used this in your model. It needs to be defined first in an iterable consisting of another iterable with two elements - `help_text`: This is the text with information about the field which you want to display to your users when they fill up any form ## Meta options Meta meaning data about data. - `ordering`: When you retrieve data from DB using the view function in your views.py, you can set the order in which the objects are returned in the view function itself. - `verbose_name`: This is to set a name for the model which is easy to read. The Munged version of the class name is used by default like a model class name StudentDetail will become student detail. ## Model methods There are model managers and model methods. - **Model managers** are classes implemented at the table level. - **Model methods** are implemented at the row-level or instance/object level. The model methods, also known as model instance methods like get_absolute_url method. ** example of method usage directly in template*** ## Sample model ```python 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() ``` It translates into table ```sql 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 ); ``` The name of the table is a combination of app name and model name that can be changed further. The created table contains an auto-created id field. Django automatically gives every model an autoincrementing integer primary key field called id. Each Django model is required to have a single-column primary key. ## Linking Models Django ORM offers 3 ways to link models − 1. one-to-one, 2. many-to-many, and 3. many-to-one. One of the first case we will see here is the one-to-many relationships. many-to-many relationships. In our example models, Book has a ManyToManyField called authors. ### ManyToOne - `on_delete = models.CASCADE`: If the source object is deleted, then the related objects will also be deleted. - `on_delete = models.PROTECT`: This is used to protect the reference data from being deleted if the source object is deleted. - `on_delete=models.SET_NULL`: This is used to set the referenced object ForeginKey field to null if the source object is deleted. - `on_delete=models.SET_DEFAULT`: This is used to set the default value of the ForeginKey field if the source object is deleted. - `on_delete=models.SET(define_method)`: This option is used when you have any particular value or method defined which returns a value and you want that value to be saved in the ForeginKey field if the source object is deleted. - `on_delete=models.DO_NOTHING`: This is used when you do not want any action taken when the source object is deleted. ## Advantages - It ties us to MySQL. If, down the road, we switch from MySQL to PostgreSQL, we'll have to use a different database adapter (e.g., psycopg rather than MySQLdb), alter the connection parameters, and—depending on the nature of the SQL statement—possibly rewrite the SQL. ## Connecting models There may be scenarios where you have to use the same model class in different apps or situations in which you have to create a model class outside your app. This is not a problem. Example: from appName.models import modelClassName:

This post is written by Pravin

Tags : Django

Share it :      

Leave a comment




  1. GitHub
Ad below