ORM-model relationship of Django

Model Class Relationships

1) One-to-many relationship
Example: Books - Heroes
models.ForeignKey() is defined in multiple classes.

2) Many-to-many relationship
Example: News-News Type Sports News International News
models.ManyToManyField() can be defined in any class.

3) One-to-one relationship
Example: Employee Basic Information Class - Employee Details Class - Employee Work Number
models.OneToOneField defines which class can be used.

 

Many-to-many examples

# News Type Class
class NewsType(models.Model):
    # Type name
    type_name = models.CharField(max_length=20)
    # Relational attributes, representing the information below the type
    type_news = models.ManyToManyField('NewsInfo')

# News
class NewsInfo(models.Model):
    # News Title
    title = models.CharField(max_length=128)
    # Release time
    pub_date = models.DateTimeField(auto_now_add=True)
    # information content
    content = models.TextField()
    # Relational attributes, Represents the type to which the information belongs
    # news_type = models.ManyToManyField('NewsType')
Many-to-many examples
# Employee Basic Information Class
class EmployeeBasicInfo(models.Model):
    # Full name
    name = models.CharField(max_length=20)
    # Gender
    gender = models.BooleanField(default=False)
    # Age
    age = models.IntegerField()
    # Relational attributes,Details on behalf of employees
    employee_detail = models.OneToOneField('EmployeeDetailInfo')

# Employee Details Class
class EmployeeDetailInfo(models.Model):
    # Contact Address
    addr = models.CharField(max_length=256)
    # Educational Experience
    # Relationship attributes, representing basic employee information
    # employee_basic = models.OneToOneField('EmployeeBasicInfo')
One-to-one relationship example

Focus on one-to-many relationships;

 

Model-Associated Query

Association Query - One-to-Many

Query and Object Associated Data

In a one-to-many relationship, one-to-many classes we call it a class, many-to-many classes we call it a multiclass, and we call the class attributes defined in the multiclass to be related attributes.
Example: Query information about heroes associated with books with id 1.

b=BookInfo.objects.get(id=1)
b.heroinfo_set.all()
//Query through a model class:
HeroInfo.objects.filter(hbook__id=1)

Example: Query the book information associated with the hero with id 1.

h = HeroInfo.objects.get(id=1)
h.hbook
Query through a model class:
BookInfo.objects.filter(heroinfo__id=1)

 

Format:

When querying multiple classes by one class of objects:
One class object. Multi-class name lowercase_set.all() #Data for query
When one class is queried by a multiclass object:
Objects of multiple classes. Associated properties#Query objects of multiple classes for one class
When the id of a class of objects is queried by a multiclass object:
Multiclass objects. Associated attribute_id

 

Implementing associated queries through model classes

Association Query
1. When implementing an associated query through a model class, you need to check which table contains the data through which class.
2. When writing a related query condition, if there are no relationship attributes in the class, the condition needs some corresponding class names. If there are relationship attributes in the class, write the relationship attributes directly.

Example: Query book information, requiring the description of the hero associated with the book to include'eight'.

BookInfo.objects.filter(heroinfo__hcomment__contains='eight')

Example: To query book information, ask the hero's id in the book to be greater than 3.

BookInfo.objects.filter(heroinfo__id__gt=3)

Example: Query all the heroes named "Eight Dragons".

HeroInfo.objects.filter(hbook__btitle='Eight parts of Dragon')

 

Query one type of data through multiple classes of conditions:
Class name.objects.filter (multi-class name lower case_u multi-class attribute name_u condition name)
Query multiple classes of data through one class of conditions:
Multiple class names.objects.filter (Associated Attribute_u Class Attribute Name_u Conditional Name)

 

 

Model - Insert and Delete

Insert, update, and delete
Insertion and updating of the corresponding data table of a model class can be accomplished by calling the save method of a model class object.
The delete method of a model class object can be called to delete the corresponding data table of the model class.
Insert example:

# 1.Establish bookinfo object
b = models.BookInfo()
b.btitle = "Meteor Butterfly Sword"
b.bpub_date = date(1990, 1, 1)
# 2.Save in database
b.save()

Delete example:

# 1.Get Book Objects
book = models.BookInfo.objects.get(id=bid)
# 2.Delete Books
book.delete()

 

Model-Autocorrelation

Autocorrelation is a special one-to-many relationship.
Case: Show upper and lower levels of Guangzhou.
Region table: id, atitle, aParent_id;
Batch execution of SQL statements in mysql terminal: source areas.sql;

 

Self-Related Cases

models.py

class AreaInfo(models.Model):
    """Regional Model Class"""
    # Area Name
    atitle = models.CharField(max_length=20)
    # Relationship attribute, representing the parent region of the current region
    aParent = models.ForeignKey("self", null=True, blank=True)

 

E:\Pycharm\Pycharm_save\cp15\test2>cd booktest

E:\Pycharm\Pycharm_save\cp15\test2\booktest>mysql -uroot -p
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use test1000;
Database changed
mysql> source area.sql

 

area.html

<h1>region</h1>
<p>{{ area }}</p>

<h1>Parent Region</h1>
<p>{{ parent }}</p>

<h1>Sub-region</h1>
<ul>
    {% for child in children %}
        <li>{{ child }}</li>
    {% endfor %}
</ul>

Views.py

def areas(request):
    '''Get upper and lower levels of Guangzhou'''
    # 1.Get information about Guangzhou
    area = AreaInfo.objects.get(atitle='Guangzhou City')
    # 2.Query the superior areas of Guangzhou
    parent = area.aParent
    # 3.Query the subordinate address of Guangzhou
    children = area.areainfo_set.all()
    # Using templates
    return render(request, 'booktest/areas.html', {'area': area, 'parent': parent, 'children': children})

Urls.py

from django.conf.urls import url
from booktest import views

urlpatterns = [
    url(r'^areas/$', views.areas),  # Self-Related Cases
]

Note the'/'following the url in the browser.

 

 

Model-Model Manager

What is Manager?

What is BookInfo.objects.all()->objects?
A: Objects are manager objects that Django automatically generated for me, through which data can be queried.
Objects are an object of the models.Manger class.After customizing the manager, Django no longer helps us build the default objects manager.

 

Custom Manager

You can customize a book = models.Manager() under BookInfo
Instead of using BookInfo.objects.xxx, you can use BookInfo.book.xxx, but that doesn't help.
We usually do this:

 

Application scenarios for custom manager classes

1) Change the result set of the query.
For example, a call to BookInfo.books.all() returns data for a book that has not been deleted.
2) Add additional methods.
The Manager class defines a method to help us manipulate the data tables corresponding to the model class.
Using self.model(), you can create a model class object that corresponds to the custom manager.

 

Custom Manager Example

Custom Manager Code

class BookInfoManager(models.Manager):
    '''Book Model Manager Class'''

    # 1.Changing the result set of an existing query
    def all(self):
        # 1.Calling the parent class's all Method, get all the data
        books = super().all()  # QuerySet
        # 2.Yes books Data filtering in
        books = books.filter(isDelete=False)
        # Return books
        return books

    # 2.Encapsulation method to manipulate data tables corresponding to model classes (add delete check)
    def create_book(self, btitle, bpub_date):
        '''Add a Book'''
        # 1.Create a Book Object
        # Obtain self Model class in which
        model_class = self.model
        book = model_class()
        # book = models.BookInfo()
        book.btitle = btitle
        book.bpub_date = bpub_date
        # 2.Add to Database
        book.save()
        # 3.Return book
        return book


# A Class
# booktest2_bookinfo
class BookInfo(models.Model):
    '''Book Model Class'''
    # Book Name
    btitle = models.CharField(max_length=20, db_column='title')
    # Book Name Unique
    # btitle = models.CharField(max_length=20, unique=True, db_index=True)
    # Price,Maximum number of bits is 10,Decimal 2
    # bprice = models.DecimalField(max_digits=10, decimal_places=2)
    # Date of publication
    bpub_date = models.DateField()
    # bpub_date = models.DateField(auto_now_add=True) # Creation Time
    # bpub_date = models.DateField(auto_now=True) # Update Time
    # Reading volume
    bread = models.IntegerField(default=0)
    # Comments
    bcomment = models.IntegerField(default=0)
    # Delete Tag
    isDelete = models.BooleanField(default=False)

    # book = models.Manager() # Customize a Manager class object, Manager object
    objects = BookInfoManager()  # Customize one BookInfoManager Object of class

    # @classmethod
    # def create_book(cls, btitle, bpub_date):
    #     '''Add a Book'''
    #     # Create an object of cls class
    #     obj = cls()
    #     obj.btitle = btitle
    #     obj.bpub_date = bpub_date
    #     # Add to Database
    #     obj.save()
    #     # Return obj
    #     return obj
Custom Manager Code

 

Use of Custom Manager:
1.BookInfo.objects.all() # objects are objects in the manager and return a value of isDelete=0;
2.
from booktest.models import BookInfo
BookInfo.objects.create_book('test2', '1991-1-1')

 

In fact, the create method has been encapsulated in models.Manager, using the following example:
BookInfo.objects.create(btitlt='test3', bpub_date='1991-1-1')

 

Note that if the defined book model class name is changed, such as class BookInfo, then book = BookInfo() in BookInfoManager should also be changed to
book = BookInfo1(), which can be cumbersome, but fortunately, Manager has this in mind.

# Obtain self Model class in which
model_class = self.model
book = model_class()

# The above two sentences correspond to the last one.
#  book = BookInfo()

 

Summary:

Purpose: Model manager classes and model classes are defined by objects = BookInfoManager() in the model class and are passed through in the model manager class
model_class = self.model; book = model_class() to establish a relationship.

 

 

Model-Meta Options

Django default generated table name: lowercase the name _model class name.

Meta-option: You need to define a meta-class in the model class where you can specify the table name by defining a class attribute, db_table.

If you change the application name and the table name does not change automatically, you will have problems.
To solve this problem, we need to make the table name of the model class independent of the application name.
Use the meta option to specify the table name.

class BookInfo(models.Model):
    '''Book Model Class'''
    btitle = models.CharField(max_length=20, db_column='title')
    bpub_date = models.DateField()
    bread = models.IntegerField(default=0)
    bcomment = models.IntegerField(default=0)
    isDelete = models.BooleanField(default=False)
    
    objects = BookInfoManager()  # Customize one BookInfoManager Object of class
  
   # Use meta options class Meta: db_table = 'bookinfo' # Specify the corresponding table name for the model class

Tags: Python MySQL Attribute Database Django

Posted on Sun, 25 Aug 2019 19:41:47 -0700 by Fazer