Django learns the timeline Model

Source: Internet
Author: User

Orm: ing between object databases and models. If you want to operate the database in a simple way, such as using a class, it is like P = person. get (ID = 1), you must map the code to the database structure, you can create a set of classes and their corresponding relationships to the database tables in advance, or track the database structure in real time. Obviously, the second method affects efficiency, so most of the time, at the beginning, a model is used to correspond to a relationship in the database, and then the structure of the database is ensured to be uniform, so that the SQL statements can be highly encapsulated and the business logic can be operated in a concise and clear way, like P = person. get (ID = 1), you get an instance (information) of the person table in the database ). Of course, it is complicated to implement such an encapsulation framework by yourself. Django has a powerful model system.

The model uses classes to represent database tables. Each class attribute is a field in the Table. Of course, this attribute must be a field subclass provided by Django. Let's first create a very simple model. Configure Django and create a Django project.

#-*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
# Create your models here.
class User(models.Model):
name = models.CharField(max_length=10)
sex = models.CharField(max_length=10)

In this way, a model is created. This model creates a user table in the database and has a name column and sex column. They are of the varchar type. Modes provides many field types.

In charfield (max_lenght = 10), max_lenght is a required field, indicating its length. If you need a large text with an infinite length, you can use textfield. Commonly Used fields include emailfield,

Urlfield, ipaddressfield, booleanfield, nullbooleanfield, and filefield (save files). For details, see the official documents. They all inherit from the field class and are in the models block. Generally, you can use

Integerfield indicates a number. The input primary_key = true can be defined as the primary key.

By default, the system generates its own primary key. Now I want to write the second class. Now we have the user class. We can assume that the group of users may be members of several teams, and one person can only join one team, first, you must have a team.

Class

#-*- coding:utf-8 -*-from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezone# Create your models here.class User(models.Model):    name = models.CharField(max_length=10)    sex = models.CharField(max_length=10)class Team(models.Model):    name = models.CharField(max_length=10)

 

In this way, a team class is added, and a one-to-multiple link foreign key is used for the start setting, so foreignkey (Team) is used, as shown in the following figure.
#-*- coding:utf-8 -*-from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezone# Create your models here.class User(models.Model):    name = models.CharField(max_length=10)    sex = models.CharField(max_length=10)    team = models.ForeignKey(Team)class Team(models.Model):    name = models.CharField(max_length=10)

However, if an error occurs during synchronization, because the team does not have an explanation under the user, an error is reported. Generally, enter Python manage. PY makemigrations creates a historical migration file, and then migrate executes the migration, it will be synchronized to the database. in order not to report an error, it should be like this:

#-*- coding:utf-8 -*-from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezone# Create your models here.class Team(models.Model):    name = models.CharField(max_length=10)class User(models.Model):    name = models.CharField(max_length=10)    sex = models.CharField(max_length=10)    team = models.ForeignKey(Team)

At this time, the user group may be friends. The relationship between friends is many-to-many. A person may have many friends, and each friend may have many friends. Therefore, there is many-to-many relationship, as follows:

#-*- coding:utf-8 -*-from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezone# Create your models here.class User(models.Model):    name = models.CharField(max_length=10)    sex = models.CharField(max_length=10)    team = models.ForeignKey(Team)    friend = models.ManyToManyField(‘self‘)class Team(models.Model):    name = models.CharField(max_length=10)

'Self 'indicates you are yourself. If you are using a team to input class variables, it is also applicable to foreign keys. By default, Django indicates that if you are a friend of mine, I am also a friend of mine. Using the parameter 'effecrical = false' can break this symmetry. If necessary, you can use it in manytomanyfield.

If some teams are special, they not only have names, but also have special fields, such as tanks, but they are also teams. They can be inherited or onetoonefield (Team). The inheritance is as follows:

#-*- coding:utf-8 -*-from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezone# Create your models here.class User(models.Model):    name = models.CharField(max_length=10)    sex = models.CharField(max_length=10)    team = models.ForeignKey(Team)    friend = models.ManyToManyField(‘self‘)class Team(models.Model):    name = models.CharField(max_length=10)class SuperTeam(Team):    tank = models.CharField(max_length=10)

This may not show the advantages of inheritance. If the team class has 10 thousand attributes and the superteam has ten thousand and one attributes, the first 10 thousand attributes are the same as those of the team.

Sometimes the inheritance may not require a team, that is, the team is not actually used. You can set the team to an abstract inheritance class, and the database will not create this table. It only exists for inheritance, in the meta nesting class of the team

Define Abstruct = true, just like this:

#-*- coding:utf-8 -*-from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezone# Create your models here.class User(models.Model):    name = models.CharField(max_length=10)    sex = models.CharField(max_length=10)    team = models.ForeignKey(Team)    friend = models.ManyToManyField(‘self‘)class Team(models.Model):    name = models.CharField(max_length=10)    class Meta:        abstract = Trueclass SuperTeam(Team):    tank = models.CharField(max_length=10)

For details about nesting classes, refer to the official documentation.

The multi-to-many relationship is actually to create a third table in the database to store this relationship. Sometimes if you want this table to have fields, you can write this table by yourself, for example, the time when a user becomes a friend.

#-*- coding:utf-8 -*-from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezone# Create your models here.class User(models.Model):    name = models.CharField(max_length=10)    sex = models.CharField(max_length=10)    team = models.ForeignKey(Team)    friend = models.ManyToManyField(‘self‘,through=‘FriendShip‘)class Team(models.Model):    name = models.CharField(max_length=10)    class Meta:        abstract = Trueclass SuperTeam(Team):    tank = models.CharField(max_length=10)class FriendShip(models.Model):    user = models.ForeignKey(User)    friend = models.ForeignKey(User)    data_became_friend = models.DateTimeField(default=timezone.now)

First, use through to specify the table for which you want to become a friend relationship, and then define this relationship in the third table. This is also true if there are many-to-many relationships between different classes, there is only one foreign key pointing to another table that becomes a friend. However, there is a conflict here. If there are more than three foreign key users in the relational table, for example, like this

class FriendShip(models.Model):
user = models.ForeignKey(User,relat_name = ‘user_set‘)
friend = models.ForeignKey(User)
three = models.ForeignKey(User)
data_became_friend = models.DateTimeField(default=timezone.now)

Django is not smart enough to tell which field he wants to match, because it is originally a friend relationship between the two, and it is inexplicably a third, at this time, you need to add the through_fields = ('user', 'friend') parameter to the foreign key. Similarly, if there are many-to-many pairs of different classes, you should also write parameters in order.

 

As for operations, Django provides manage and queryset.

Objects is a variable that only needs manage for each class. It is obtained by manage and provides the all filter exclude get method to return the queryset object. queryset also provides the manage method, so the last step is to support the concatenation operation, just like, get (ID = 1 ). filter (name _ contains = "Tree"), Django also provides many filtering operations such as _ contains. You only need to name _ contains. Update is used for modification, or attribute assignment is used for modification. This modification also modifies unmodified values according to the original values. Finally, the SAVE Function will execute the result in the database. This is a kind of Inertia Mechanism, and I will not execute the result immediately.



 



Django learns the timeline Model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.