preface

  • The general steps for djangoWeb development, as shared in previous articles, are:
    • Creating a Virtual Environment
    • Install django
    • Create a project
    • Create an
    • Create model classes in model.py
    • Defining a view
    • Configure the url
    • Create a template

1. Introduction of ORM

  • MVC framework has an important part, is ORM, it realizes the decoupling of data model and database, that is, the design of data model does not need to rely on a specific database, through simple configuration can easily change the database
  • ORM is short for object-relations-mapping. Its main tasks are:
    • Generate database table structures based on object types
    • Convert object and list operations into SQL statements
    • Convert SQL query results into objects and lists
  • A model in Django contains fields and constraints that store data, corresponding to a unique table in the database


    ORM.png

2. Use MySql database

  • Install mysql package in virtual environment

    pip install mysql-python

  • Create a database in mysql

    create databases test charset=utf8

  • Open the settings.py file and modify the DATABASES item

    DATABASES = {

    ‘default’: {

      'ENGINE': 'django.db.backends.mysql'.'NAME': 'test'.'USER': 'Username'.'PASSWORD': 'password'.'HOST': 'DATABASE server IP address, local can use localhost'.'PORT': 'Port, default is 3306'.Copy the code

    }}

3. Django model class development process

  • Define a Model class in models.py that inherits from models.model
  • Add the app to installed_app in settings.py
  • Generate migration files
  • Perform migration to generate tables
  • Use model classes for CRUD operations

4. Define model classes

  • Defining properties in the model generates fields in the database table
  • Django determines the following information based on the type of attribute:
    • The type of field supported by the currently selected database
      • The default HTML control to use when rendering administrative forms
      • Minimum validation at admin site
  • Django adds an auto-growing primary key column to a table. Each model can have only one primary key column. If you use the option to set a primary key column for a property, Django does not regenerate the default primary key column
  • Attribute naming restrictions
    • Cannot be a Python reserved key
    • Because of the way Django queries are, consecutive underscores are not allowed

      5. Define model properties

  • When defining an attribute, you need a field type
  • The field types are defined in django.db.models. Fields and imported into Django.db.models for ease of use
  • use
    • Import from django.db import models
    • Create an object of Field type with models.Field and assign the value to the property
  • The isDelete attribute is of type BooleanField and the default value is False

    6. Define the field type

  • TimeField: The time represented using Python’s datetime.time instance, with the same argument as DateField

  • DateTimeField: The date and time represented using Python’s datetime.datetime instance, with the same arguments as DateField
  • FileField: a field used to upload files
  • ImageField: Inherits all the properties and methods of FileField, but verifies the uploaded object to make sure it is a valid image
  • AutoField: An IntegerField that grows automatically based on the actual ID. It is usually not specified
    • If not specified, a primary key field is automatically added to the model
  • BooleanField: True /false field for which the default form control is CheckboxInput
  • NullBooleanField: Supports null, true, and false values
  • CharField(max_length= character length) : string. The default form style is TextInput
  • TextField: large TextField, usually used over 4000. The default form control is Textarea
  • IntegerField: integer
  • DecimalField(max_digits=None, decimal_places=None) : Decimal floating point number represented using python’s Decimal instance
  • Decimalfield. max_digits: Total number of digits
  • DecimalField. Decimal_places: Number of digits after the decimal point
  • FloatField: A floating-point number represented by a Float instance of Python
  • DateField[auto_now=False, auto_now_add=False]) : the date represented by Python’s datetime.date instance
    • Parameter datefield. auto_now: This field is automatically set to the current time each time an object is saved for the “last modified” timestamp, which always uses the current date and defaults to false
      • Parameter datefield. auto_now_add: The timestamp used for creation, which automatically sets the current time when the object is first created, always uses the current date and defaults to false
      • The default form control for this field is a TextInput. Added a JavaScript written calendar control to the admin site, and a “Today” shortcut button that includes an additional Invalid_date error message key
      • The auto_now_add, auto_NOW, and default Settings are mutually exclusive, and any combination of them will produce incorrect results

7. Field options in model classes

  • Field options allow you to constrain fields
  • Specified by keyword argument in field object
  • Null: If True, Django stores null values to the database as null. The default value is False
  • Blank: This field is allowed to be blank if True. The default is False
  • Contrast: NULL is a database category, blank is a form validation category
  • Db_column: Specifies the name of the field. If not specified, the name of the property is used
  • Db_index: If True, an index will be created for this field in the table
  • Default: indicates the default value
  • Primary_key: If True, this field becomes the primary key field of the model
  • Unique: If True, this field must have a unique value in the table

8. Relationships between model classes

  • The types of relationships include
    • ForeignKey: One-to-many, which defines fields in the many end
    • ManyToManyField: Many-to-many, defining fields on both ends
    • OneToOneField: One to one, the field is defined on either end
  • You can maintain recursive associations, specified by ‘self’, which is “self-association”.
  • Access many: objects with one. The model class lowercase _set

    mytestinfo.testinfo_set.all()

  • Use one to access one: object. Model class lowercase

    testinfo.mytestinfo

  • Access ID: object. Attribute _id

    testinfo.mytest_id

9. Define class Meta in the model class

  • Meta information DB_TABLE: Defines the name of the data table. Lowercase letters are recommended, and the default name of the data table is used

    < application name >_< Model class name >

  • Ordering: This field is used to get the list of objects without ordering

    class TestInfo(models.Model):

               class Meta():
                         ordering = ['id']Copy the code
  • The string is preceded by – to indicate reverse order; the string is not preceded by – to indicate positive order

    class TestInfo(models.Model):

    class Meta():

      ordering = ['-id']Copy the code

10. Manager for model classes

  • Objects: Objects of type Manager used to interact with a database
  • When you define a model class without specifying a manager, Django provides a manager named Objects for the model class
  • Supports managers that explicitly specify model classes

    class BookInfo(models.Model):

    books = models.Manager()

  • When you specify a manager for a model class, Django no longer generates a default manager named Objects for the model class

  • The manager is the interface through which Django models perform database queries, and every model in a Django application has at least one manager

  • Custom manager classes are used in two main cases

    • Add additional methods to the manager class to create a manager object to save data to the database

      class TestInfoManager(models.Manager):

      def create_test(self, title, update):

      test = self.model()

      test.isDelete = False

      return test

      class TestInfo(models.Model): Tests = TestInfoManager() call: book= testinfo.tests.create_ test(” ABC “,datetime(1980,1,1)) save: test.save()

    • Modify the original queryset returned by the manager: override the get_queryset() method

      class TestInfoManager(models.Manager):

      def get_queryset(self):

      return super(TestInfoManager, self).get_queryset().filter(isDelete=False)

      class TestInfo(models.Model):

      tests = TestInfoManager()

  • Django doesn’t read or write to the database when creating objects

  • In the manager’s methods, self.model is used to get the model class to which it belongs
  • The save() method is called to interact with the database to save the object to the database
  • Constructing model objects using keyword arguments is cumbersome, and two of the following are recommended
  • Description:init Method is already used in the base class models.model and cannot be used in custom models
  • Add a class method to the model class to save data to the database

    class BookInfo(models.Model):

    @classmethod

    def create(cls, title):

      test = cls(btitle=title)
      test.isDelete = False
      return testCopy the code

    Call: test= testinfo.create (“hello”); Save: the test. The save ()

  • DoesNotExist: this exception is raised when the object of the model DoesNotExist when making a single query, used with try/except

  • Instance methods
    • STR (self) : Overrides the object method, which is called when an object is converted to a string
      • Delete () : Deletes the model object from the table

11. Model class query

  • A query set represents a collection of objects retrieved from a database
  • The query set can have zero, one, or more filters
  • Filters restrict the results of the query based on the parameters given
  • From an Sql perspective, query sets are equivalent to SELECT statements, and filters are like WHERE and limit clauses
  • The following points are mainly discussed
    • Query set
    • Field query: comparison operator, F object, Q object
      (1) Model class query set
  • Calling the filter method on the manager returns a set of queries
  • The query set is filtered by a filter and returns a new query set, so it can be written as a chain filter
  • Lazy execution: Creating a query set does not bring any access to the database until the data is invoked
  • When to evaluate a query set: iteration, serialization, and if
  • Methods that return a query set, called filters, and the manager object methods are all(), filter(), exclude(), order_by(), and values().

  • A method that returns a single value

    • Get () : Returns a single object that meets the criteria
    • Raises the “model class” if not found. Abnormal DoesNotExist”
    • If more than one is returned, the “model class” is raised. Abnormal MultipleObjectsReturned”
    • Count () : Returns the total number of queries
    • First () : Returns the first object
    • Last () : Returns the last object
    • Exists () : checks whether there is data in the query set. If there is data in the query set, True is returned
  • Restrict the query set, if an object is retrieved, directly use [0]
  • A cache of model query sets

    • This makes up two query sets, the cache cannot be reused, and each query interacts with the database once, increasing the database load

      print([e.title for e in Entry.objects.all()])

      print([e.title for e in Entry.objects.all()])

      • Loop through the same query set twice, using data from the cache the second time

        querylist=Entry.objects.all()

        print([e.title for e in querylist])

        print([e.title for e in querylist])

  • When to set the query will not be cached: when only part of the query set is evaluated when check the cache, but if this part is not in cache, then the query returns the records will not be cached, which means using index to limit the query set will not populate the cache, if this part of the data is cached, use the cached data directly

  • Comparison operator: Represents two underscores, the property name on the left and the comparison type on the right

    • Exact: indicates judgment and is case-sensitive. If the comparison operator is not written, it is judged and so on

      filter(isDelete=False)

    • Contains: Whether contains, case sensitive

      Exclude (btitle__contains = ‘pass’)

      • Startswith, endswith: starts or endswith value and is case-sensitive

        Exclude (btitle__endswith = ‘pass’)

      • Isnull, isnotnull: indicates whether the value isnull

        filter(btitle__isnull=False)

      • I is used to indicate case-insensitive, such as iexact, icontains, istarswith, and iendswith

      • In: Indicates whether it is included in the range

        filter(pk__in=[1, 2, 3, 4, 5])

      • Gt, GTE, LT, and LTE: Greater than, less than, less than or equal to

        filter(id__gt=3)

      • Year, month, day, week_day, hour, minute, second: computes attributes of the day period type

        filter(bpub_dateyear=1980)

        filter(bpub_date
        gt=date(1980, 12, 31))

      • Queries across associations: Handle join queries

        Heroinfohcontent__contains =’ 8 ‘; heroinfohContent__contains =’ 8 ‘; heroinfohcontent__contains=’ 8 ‘;

      • The shortcut for query is pk, where PK indicates the primary key and the default primary key is ID

        filter(pk__lt=6)

(2) Aggregation function
  • Use the aggregate() function to return the value of the aggregate function
  • Functions: Avg, Count, Max, Min, Sum

    from django.db.models import Max

    maxDate = list.aggregate(Max(‘bpub_date’))

  • The general use of count:

    count = list.count()

(3) F object
  • Field A of the model can be compared with field B. If A is written to the left of the equals sign, B appears to the right of the equals sign and needs to be constructed with an F object

    list.filter(read__gte=F(‘commet’))

  • Django supports arithmetic operations on F() objects

    list.filter(read__gte=F(‘commet’) * 2)

  • F() object can also be written as “model class __ column name” for associated query

    list.filter(isDelete=F(‘testinfo__isDelete’))

  • For date/time fields, you can operate with timedelta()

    list.filter(update__lt=F(‘update’) + timedelta(days=1))

(3) Q object
  • The keyword parameter query in the filter method will be combined with And
  • To do an OR query, use the Q() object
  • The Q object (django.db.models.q) is used to encapsulate a set of keyword arguments that are the same as those in the comparison operator

    from django.db.models import Q

    list.filter(Q(pk_ _lt=6))

  • Q object can use & (and), | (or) operator

  • When the operator is applied to two Q objects, a new Q object is generated

    list.filter(pk_ lt=6).filter(bcommet gt=10)

    list.filter(Q(pk
    lt=6) | Q(bcommet _gt=10))

  • Use the ~ (not) operator to indicate negation before a Q object

    list.filter(~Q(pk__lt=6))

  • Can use & | ~ combined with parentheses to group, complex structure business Q object

  • Filter functions can pass one or more Q objects as positional arguments, and if there are more than one Q object, the logic of these arguments is AND
  • Filter functions can mix Q objects with keyword arguments, all arguments will be and together, and the Q object must precede the keyword argument

12. Model self-correlation

  • For locale information, which belongs to a one-to-many relationship, a single table is used to store all information
  • A similar table structure is also applied to categorizing information, allowing for an infinite level of categorization

    class AreaInfo(models.Model):

    atitle = models.CharField(max_length=20)

    aParent = models.ForeignKey(‘self’, null=True, blank=True)