Django framework Advanced Common Fields 5 models and parameters, parameter choices, sql automatically display configuration command, query optimization orm relevant transaction operations in orm, MTV and MVC model library management system (CRUD Books)

The models used in the fields

AutoField (primary_key = True) primary key (int auto increment, must fill in the parameters primary_key = True. When the model, if there is no auto-increment, then automatically creates a column named id column.)

CharField(max_length=32)     varchar(32)

IntegerField()       int

BigIntergerField()           bigint

DecimalField () decimal

EmailField()       varchar(254)

DateField()     date

DateTimeField()  datetime

  auto_now: each time you edit data when the time will automatically update the field

  auto_now_add: When creating the data is automatically updated

BooleanField(Field)

  The field to pass Boolean values ​​will film into digital 0/1

  is_delete

  is_status

  is_vip

TextField(Field)

  - text types to store large pieces of text

FileField(Field)

  - string path stored in the database, upload files to a specified directory, only keep the file path

    upload_to = 'specify the file path'

    This field transmission path to file object file is automatically saved to the specified folder upload_to then save the file field

 

How to customize the char type field

from django.db.models Import Field, 

class RealCharField (Field,):
     DEF  the __init__ (Self, MAX_LENGTH, args *, ** kwargs): 
        self.max_length = MAX_LENGTH   # intercept method using a super call parent class parent class after completing the operation method 
        Super (). the __init__ (MAX_LENGTH = MAX_LENGTH, args *, ** kwargs) 

    DEF db_type (Self, Connection):
         return  ' char (% S) ' % self.max_length 
        
class Movie (models.Model): 
    the textField = RealCharField ( max_length = 64)

 

Critical parameters in the field

  null null = True  allow field is empty , you must be null

  default default parameters

  django 1.x is the default cascade delete cascading update requires you to manually specify django2.x

    on_delete = models.CASCADE

    db_contraints = True

    # Baidu

 

choice parameters

  Users of sex
  education
  Marital status
  job status
  customers source
  when you list your data can be completely you can consider using the parameter choices

models.py

class Userinfo (models.Model): 
    username = models.CharField (MAX_LENGTH = 32 ) 
    gender_choices = ( 
        ( . 1, ' M ' ), 
        ( 2, ' F ' ), 
        ( 3, ' other ' ), 
    ) 
    Gender = Models. IntegerField (choices = gender_choices)
     # the field of digital memory and may be matched or a number other than the relationship 
    record_choices = (( ' the checked ' , ' checked in ' ), 
                      (' Vacate ' , ' leave ' ), 
                      ( ' NOSHOW ' , ' absence ' ), 
                      ( ' leave_early ' , ' leave early ' ), 
                      ) 
    Record = models.CharField ( ' class record ' , = record_choices choices, default = ' the checked ' , max_length = 64)

test.py

= models.Userinfo.objects.get USER_OBJ (PK = 1 )
 Print (user_obj.username)
 Print (user_obj.gender)
 # For choices parameter field value when get_xxx_display () 
Print (user_obj.get_gender_display ())
 # for no comment data information get_xxx_display () or the number itself acquired 
USER_OBJ = models.Userinfo.objects.get (= PK. 4 )
 Print (user_obj.gender)         # 100 
Print (user_obj.get_gender_display ())     # 100

 

sql django automatically display commands to configure

settings.py file added

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

 

Database query optimization (interview will ask)

only与defer

only the role of 
the results obtained in parentheses pass field is a field containing specified in brackets in the list of sets of data attributes of the object to only
the object point of the field attribute is not going to go the database but once you point field in the non-bracketed can take the data
but is now re-take the database query
defer and only opposite 
results in parentheses pass field get is a list of sets of data objects within the object is not specified in the field attribute parentheses
target point will duplicate the field attribute database but once you take the point field in the non-bracketed not gone database the
 # RES = models.Book.objects.all () # Django ORM queries that are inert query 
    # Print (RES) 


    # RES = models.Book.objects.values ( 'title') 
    # Print (RES) 
    # for R & lt RES in : 
    #      Print (r.title) 

    # RES = models.Book.objects.only ( 'title') # only objects inside these properties title 
    # # Print (RES) 
    # for R & lt RES in: 
    #      # Print (r.title) 
    #      Print (r.price) # interior will re-iterate, look for the price 
    "" " 
    only the role of 
        the results obtained in parentheses pass field is a list containing only the specified set of data objects in parentheses field properties within that object 
        subject property is a point of the field will not take the database but once you point field in the non-bracketed can get data 
        but is re-take the database query it 
    . "" " 

    #res = models.Book.objects.defer ( 'title') # defer only mutually inverted relationship with 
    # for R & lt RES in: 
    #      Print (r.title) 
    "" " 
    the defer only contrast with 
        the results obtained in parentheses is transmitted field a list of sets of data objects within the object is not specified in the field attribute parentheses 
        target point will duplicate the field attribute database but once you take the point of the field in the database non brackets will not go 
    . "" "
View Code

selected_related与prefetch_related

selected_related

interior is now operating table even after all the linked table and then check out a one-time package to object
after the data objects in acquiring data from any table when the database do not need to walk the entire package because the property became the object

select_related brackets could send the foreign key field and not only is many-to-many and one field
select_related (foreign key fields 1__ foreign key fields 2__ ... foreign key field. 3)

prefetch_related
prefetch_related internal subquery but you feel even to operating table 
inside the subquery by the foreign key data page management table to all encapsulated into objects you
target point after the current table or foreign key fields in the table is also not You need to take the database
Advantages and disadvantages
Even select_related table operations that take advantage of sql query only once 
time-consuming operation consumption in the connection table of 10s

prefetch_related subquery go twice sql query
time-consuming and 1s in the number of queries
 # Select_related and prefetch_related 
    # RES = models.Book.objects.get (= PK. 1) 
    # Print (res.publish.name) 

    # RES models.Book.objects.select_related = ( 'publish') 
    # for R & lt RES in: 
    #      Print (r.publish.name) 
    #      Print (r.publish.addr) 
    "" " 
    internal table even after the operation of the entire table will now be further linked to a disposable package check out the object 
    after obtaining any data object table when the data do not need to walk all packaged in a database as the attribute of the object 
    
    within the brackets can pass select_related foreign key field and not only is many-to-many and one field 
    select_related (foreign key field 1__ foreign key fields 2__ ... foreign key field. 3) 
    "" " 

    # prefetch_related 
    # RES = models.Book.objects.prefetch_related ( 'publish') 
    # # Print (RES) 
    #
    # For r in RES: 
    #      Print (r.publish.name) 

    "" " 
    prefetch_related internal subquery but give you the feeling that even the operating table 
    inside by the sub-query data page management table foreign key to the whole package to you object 
    after the object point in the current table or the foreign key fields in the table also do not need to take the database 
    "" " 
    " "" 
    advantages and disadvantages 
    select_related even operating table that benefits go only once sql query 
        operation takes a lot of tables in connection 10s 
        
    prefetch_related subquery go twice sql query 
        time-consuming and in the number of inquiries 1S 
    "" "
View Code

 

How django orm open transaction operations

Four characteristics of the transaction (ACID)

  Atomicity

  consistency

  Isolation

  Endurance

start transaction
rollback
commit

Code:

# Django ORM open transaction operations 
from django.db Import Transaction 
with transaction.atomic (): 
    # ORM statements executed with the code blocks belong to the same transaction 
    Pass 

# block of code to run other end of the transaction is over you can configure transaction-related Baidu Soso look

 

MTV and MVC model

MTV django framework known as MTV

  M:models

  T:templates

  V: views

MVC

  M:models

  V: views

  C: controller controller (route distribution urls.py)

Nature: MTV is the essence of MVC

 

BMS Library Management System

  

Guess you like

Origin www.cnblogs.com/ludingchao/p/12172611.html