This article is participating in “Python Theme Month”. Check out Python Authoring season to show off your Python articles – $2000 limited prize waiting for you to win

Models model

ORM


  • ObjectRelationMap: Convert object-oriented thought to relational database thought, operation class equivalent to a table
  • Class corresponding table
  • Properties in a class correspond to fields in a table
  • Define the class in the models.py file in your application
  • All classes that need to use ORM must be subclasses of Models.model
  • All attributes in class correspond to fields in the table
  • Fields must be typed using modles. XXX instead of python types
  • In Django, Models are responsible for interacting with the database

Django connecting to a database

  • The default database is Sqlite3
    • Relational database
    • lightweight
  • Splite3 is recommended for development and mysql for deployment
    • Switching databases is set in Settings

      Mysql database = ['default' = {'ENGINE': 'django.db.backends'; mysql database = [' database '= {'ENGINE': 'django.db.backends'; mysql database = [' database' = {'ENGINE': 'django.db.backends'; Database password ', 'HOST': '127.0.0.1', 'PORT': '3306',}]Copy the code
    • The Pymysql package needs to be imported into the __init__ file under the project file

      # in the main project's __init__ file
      
      import pymysql   
      pymysql.install_as_MySQLdb()
      Copy the code

Use of the Models class

Defines classes that map to database tables


  • Define the class in the models.py file in your application
  • All classes that use ORM must be models.Models subclasses
  • All attributes in class correspond to fields in the table
  • Fields must be typed using models. XXX instead of python types

Field Common parameters


  • Max_length: specifies the maximum length of a value
  • Blank: indicates whether a field is allowed to be blank. The default value is not allowed
  • Null: Controls whether to save to NULL in DB. Default is False
  • Default: the default value
  • Unique: the only
  • Verbose_name: a false name

Database migration


  1. On the command line, generate data migration statements (generate SQL statements)

     python3 manage.py makemigrations
    Copy the code
  2. On the command line, enter instructions for database migration

    Python3 manage.py migrate # If python3 manage.py migrate does not change or fails Python3 Manage. py Makemigrations Name of python3 manage.py Migrate Name of the applicationCopy the code
  3. For the default database, to avoid confusion, if there is no data in the database, the system’s own SQlite3 database can be deleted before each migration

Data related operations

View the data in the database

Python3 manage.py shell ps: Python3 manage.py shell ps: Python3 manage.py shell ps: Python3 manage.py shell ps: Python3 manage.py shell 2. Import the mapping class from the application. Models import class name 3. Use the Objects property to manipulate the database. Objects are instantiations of the Manager class in the model that actually interacts with the database. Objects.filter () queries all the contents of a table and returns a QuerySet, which is actually a list of classes containing each data object.Copy the code

To find the data

Models import Student from myapp. Models import Student # Query student.objects.all () If you want to fetch all the data objects in all the QuerySet types, you need to iterate over all the objects and reuse the objects. S = student.object.all () for each in s: Print (each.name, each.age, each.address, each.phone)Copy the code

Add data

Object = class () # Instantiate object objects with classes. Properties = value # Assign an object to the properties of the corresponding object. Save () # The save operation must be performed otherwise the data will not enter the database # python3 Manage.py shell Add data from the application name. Models import class name From myapp.models import Student # instantiate the object s = Student() # assign the attributes of the object s.name = 'ruochen' s.dress = 'XXX' s.hone = '18888888888' s.age = 18 # save data s.ave ()Copy the code

Common Search methods

  1. Common search format: Attribute name _ _ (as follows) = value
    • Gt: greater than
    • Gte: greater than or equal to
    • Lt: less than
    • Lte: less than or equal to
    • Scope of the range:
    • Year: the year
    • Isnull: indicates whether the value isnull
  2. Find the format equal to the specified value: attribute name = value
  3. Fuzzy lookup: Attribute name _ _ (use the following) = value
    • Exact: equal to
    • Iexact: case insensitive
    • The contains: contains
    • Startwith:.. At the beginning
    • Endwith:… At the end
Filter (age__lt=20) # select course from ta = teacher.objects.filter (age__lt=20) # select course from ta = teacher.objects.filter (age__lt=20) # select course from ta = teacher.objects.filter (age__lt=20) # select course from TA = teacher.objects.filter (age__lt=20) # select course from TA = teacher.objects.filter (age__lt=20  ta = Teacher.objects.filter(course__contains="a")Copy the code

Database table relationships

  • Multi-table lookup: The use of multiple tables to find more than one piece of information or more information
  • models.py
from django.db import models

# Create your models here.

class School(models.Model) :
    school_id = models.IntegerField()
    school_name = models.CharField(max_length=20)
    # teacher_set
    # my_manager = models.OneToOneField("Manager")

    def __str__(self) :
        return self.school_name

class Manager(models.Model) :
    manager_id = models.IntegerField()
    manager_name = models.CharField(max_length=20)

    # Establish a one-on-one relationship
    my_school = models.OneToOneField(School)

    def __str__(self) :
        return self.manager_name

class Teacher(models.Model) :
    teacher_name = models.CharField(max_length=20)
    my_school = models.ForeignKey("School")

class Student(models.Model) :
    student_name = models.CharField(max_length=20)
    teachers = models.ManyToManyField("Teacher")
Copy the code

1:1 OneToOne

  • Establish relationships: On either side of the model, use OneToOneField

add

  • Add the unrelated side, directly instantiate save can be

      s = School()
      s.school_id = 2
      s.school_name = "sssss"
      s.save() 
    Copy the code
  • To add the related side, use the create method

    # method 1 m = Manager() m.manager_id = 10 m.manager_name = "ruochen" m.school = s.ave () # method 2 m = Manager() m.manager_id = 10 m.manager_name = "ruochen" m.school = s.ave ( Manager.objects.create(manager_id=20, manager_name="ruo", my_school=ss[0])Copy the code

query

  • Parent table by child table: Information is directly extracted by attributes of child table

       Manager.objects.get(manager_name="ruochen").my_school.school_name
    Copy the code
  • Checking child tables by parent table: use double underscore

     In [43]: s = School.objects.get(manager__manager_name="ruochen")
     In [44]: s
     Out[44]: <School: sssss>
    Copy the code

change

  • Use save for individual changes

      In [47]: s.school_name = "111"
      In [48]: s.save()
      
    Copy the code
  • Batch changes use update

    In [53]: ss = School.objects.all()
    In [54]: type(ss)
    Out[54]: django.db.models.query.QuerySet
    In [55]: ss.update(school_name="666")
    Out[55]: 2
    In [57]: ss
    Out[57]: [<School: 666>, <School: 666>
    Copy the code
  • Whether the child table or parent table changes

  • Delete: Directly use delete

1:N OneToMany

  • One item/object in one table can have many items in another table
  • For example, a school can have many teachers, but a teacher can only work in one school
  • On the use
    • Using a ForeignKey
    • On the more side, for example, the above example is defined in Teacher’s table

add

  • Similar to the one-to-one method, add by create and new

  • Create: Fills the properties and does not need to save manually

  • New: Attributes or parameters can be empty and must be saved with save

    In [5]: t1.my_school = ss[0] In [6]: t1.save() In [7]: teacher_name = teacher_name In [5]: t1.my_school = ss[0] In [6]: t1. ts = Teacher.objects.all() In [8]: ts Out[8]: [<Teacher: Teacher object>] In [9]: ts[0].teacher_name Out[9]: Teacher_name ="ruochen2", my_school=ss[0]) In [22]: teacher_name="ruochen2", my_school=ss[0] ts = Teacher.objects.all() In [23]: ts Out[23]: [<Teacher: Teacher object>, <Teacher: Teacher object>] In [24]: ts[1].teacher_name Out[24]: 'ruochen2'Copy the code

query

  • The school and teacher’s list shall prevail

  • If you know the teacher, look up the school, then use the added relationship attribute directly

  • For example, query which school t1 teacher is from

      In [30]: t1.my_school
      Out[30]: <School: 666>
    Copy the code
  • The check

    • If you query all teachers in the school, the system automatically adds attributes to the school model

      In [34]: s1.teacher_set.all() Out[34]: [<Teacher: Teacher object>, <Teacher: Teacher object>] In [36]: S1.teacher_set.all ().filter(teacher_name=" teacher_name ") Out[36]: [<Teacher: Teacher object>]Copy the code

N:N ManyToMany

  • Indicates that the data in any table can have multiple data in the other table and vice versa
  • A typical example is the teacher-student relationship
  • In use, on either side, use the ManyToMany definition, only one side needs to be defined

add

  • Add () to student.teachers.add()

    In [2]: stus = Student.objects.all() In [3]: stus Out[3]: [] In [4]: s1 = Student() In [5]: s1.student_name = "ruochen" In [6]: In [6]: t1 = Teacher.objects.all() In [7]: t1 Out[7]: [<Teacher: Teacher object>, <Teacher: Teacher object>] In [9]: t1. Teacher_name Out[9]: 'If' In [12]: s1. Save () In [17]: s1.teachers.add(t1) In [18]: s1.teachers.all() Out[18]: [<Teacher: Teacher object>] In [19]: s1.save() In [24]: Teacher_name teacher_name Out[24]: 'teacher_name Out'Copy the code

query

  • Similar to one-to-many, the _set query is used

      In [25]: t1.student_set.all()
      Out[25]: [<Student: Student object>]
           
           
    Copy the code