Django study notes 4

4, Advanced knowledge

4.1 admin background management

  • django provides a relatively perfect interface for background management database, which can be used for invocation and testing in the development process.

  • django will collect all registered model classes and provide a data management interface for these model classes for developers to use

  • Create background management account - this account is the highest authority account in the background management

    python3 manage.py createsuperuser

  • Registering custom model classes

    If you want the model classes defined by yourself to be displayed and managed in the / admin background management interface, you need to register your own classes in the background management interface

    Registration steps:

    1. Import and register the model models class to be managed in admin.py in the application app, such as from. Models import book

    2. Call the admin.site.register method to register, such as:

      Admin.site.register (custom model class)

    usage method:

    1. Define the model manager class in < app > / admin.py

      class XXXXManager(admin.ModelAdmin):    
      	......
      
    2. Binding registers the model manager and model classes

      from django.contrib import admin
      from .models import *
      admin.site.register(YYYY, XXXXManager)# Bind YYYY model class and manager class XXXXManager
      

    Case:

    # file: bookstore/admin.py
    from django.contrib import admin
    from .models import Book
    class BookManager(admin.ModelAdmin): 
       list_display = ['id', 'title', 'price', 'market_price']
       admin.site.register(Book, BookManager)
    

    Some options:

    1. list_display controls which fields are displayed in the Admin modification list page
    2. list_display_links can control lists_ Should fields in display be linked to the object's change page
    3. list_filter setting activates Admin to modify the filter in the right column of the list page
    4. The search_fields setting enables the search box on the Admin change list page
    5. list_editable is set as a list of field names on the model, which will allow editing on the change list page

    https://docs.djangoproject.com/en/2.2/ref/contrib/admin

4.2 relationship mapping

In relational databases, all data are usually not placed in the same table, which is not easy to expand. Common relational mappings are:

  • One to one mapping
  • One to many mapping
  • Multi pair mapping

one-on-one

Syntax: onetoonefield (class name, on_delete=xxx)

class A(model.Model):
    ...
class B(model.Model):    
	attribute = models.OneToOneField(A, on_delete=xxx)

Special field option [required]

on_delete - cascade delete

  1. models.CASCADE cascade deletion. Django simulates SQL constraint ON DELETE

    The behavior of CASCADE and delete the object containing ForeignKey

  2. models.PROTECT throws ProtectedError to prevent the deletion of referenced objects; [equivalent to mysql default RESTRICT]

  3. SET_NULL is set to ForeignKey null; null=True needs to be specified

  4. SET_DEFAULT sets ForeignKey as the default value; the default value of ForeignKey must be set

  5. See official documentation for more information https://docs.djangoproject.com/en/2.2/ref/models/fields/#foreignkey

from django.db import models
class Author(models.Model):    
	"""Writer model class"""    
	name = models.CharField('writer', max_length=50)    
class Wife(models.Model):    
	"""Writer wife model class"""    
	name = models.CharField('wife', max_length=50)    
	author = models.OneToOneField(Author, on_delete=models.CASCADE)
  • Model class without foreign key [Author]:

    author1 = Author.objects.create(name = "Mr. Wang")

  • Model class with foreign key [Wife]:

    #Associate Mr. Wang obj

    Wife1 = life. Objects. Create (name = 'Mrs. Wang', author=author1)

    #Primary key value corresponding to Mr. Wang

    Wife1 = life. Objects. Create (name = 'Teacher Wang', author_id=1)

  • Query data

    1. Forward query: direct query through foreign key attributes is called forward query

    # Find author through WiFi
    from .models import Wife
    wife = Wife.objects.get(name='Mrs. Wang')
    print(wife.name, 'My husband is', wife.author.name)
    

    2. Reverse query: the party without foreign key attribute can call the reverse attribute to query the associated party

    The reverse association attribute is the instance object. The reference class name (lower case). For example, the reverse reference of the author is the author object. Wire

    When the back reference does not exist, an exception is thrown

    author1 = Author.objects.get(name = "Mr. Wang")

    author1.wife.name

One to many

One to many refers to the one to many correspondence between real things

One to many needs to specify specific roles and set foreign keys on multiple tables

grammar

When A class A object can be associated with multiple class B objects

class A(model.Model):    
	...
class B(model.Model):    
	attribute = models.ForeignKey("one"Model class for, on_delete=xx)    

ForeignKey must specify on_delete mode

Example - create model class - otm/models.py

# file: otm/models.py
from django.db import models
class Publisher(models.Model):    
	"""Publishing house [1]"""    
	name = model.CharField('name', max_length=50, unique=True)    
class Book(models.Model):    
	"""Book [many]"""    
	title = models.CharField('title', max_length=50)    
	publisher = ForeignKey(Publisher, on_delete=models.CASCADE)
  • Query data

    1. Forward query [query Publisher through Book]

    # Query through publisher properties: book.publisher
    abook = Book.objects.get(id=1)
    print(abook.title, 'The publishing house is:', abook.publisher.name)
    

    2. Reverse query [query all corresponding books through Publisher]

    # Query the corresponding books through the publishing house
    pub1 = Publisher.objects.get(name='tsinghua university press ')
    books = pub1.book_set.all()	# Obtain multiple Book data objects corresponding to pub1 through book_set
    books = Book.objects.filter(publisher=pub1)  # It can also be obtained in this way
    print("The books of Tsinghua University Press are:")
    for book in books:   
    	print(book.title)
    

Many to many

Many to many represents many to many complex relationships between objects.

  • Creating many to many in mysql depends on the third table
  • There is no need to manually create the third table in Django, and Django completes it automatically

Syntax: in any of the two associated classes, add

Attribute = models.ManyToManyField(MyModel)

class Author(models.Model):    
	name = models.CharField('full name', max_length=11)
class Book(models.Model):    
	title = models.CharField('title', max_length=11)    
	authors = models.ManyToManyField(Author)

Example

# Scheme 1: first create an author and then associate a book	
author1 = Author.objects.create(name='Miss LV')
author2 = Author.objects.create(name='Miss Wang')    
# Mr. Lu and Mr. Wang wrote a Python book at the same time    
book11 = author1.book_set.create(title='Python')
author2.book_set.add(book11)
# Scheme 2: first create a book and then associate the author	
book = Book.objects.create(title='python1')    
# Both Guo xiaonao and teacher LV participated in the creation of Python 1    
author3 = book.authors.create(name='guoxiaonao')
book.authors.add(author1)
  1. Forward query: one party with many to many attributes queries the other party

    Query all corresponding authors through Book

    At this point, many to many attributes are equivalent to objects

    book.authors.all() -> obtain book All corresponding author Information about
    book.authors.filter(age__gt=80) -> obtain book Information of corresponding authors older than 80 years old
    
  2. inverse query

    Query all corresponding books through Author

    Using the reverse attribute book_set

    author.book_set.all()
    author.book_set.filter()
    

4.3 cookies and session s

Session definition

  • From opening the browser to visit a website to closing the browser to end the visit, it is called a session

  • The HTTP protocol is stateless, which makes it difficult to maintain the session state

  • Cookies and Session are two storage technologies born to maintain Session state 2

  • cookies are storage space stored on the client browser

    The Chrome browser can be viewed through the application > > storage > > cookies of the developer tool

    Firefox browser can be viewed through the storage > > cookie of developer tools

  • cookies are stored in the browser in the form of key value pairs. Keys and values are stored in the form of ASCII strings (not Chinese characters)

  • Stored data has a lifecycle

  • The data in cookies is stored and isolated by domain and cannot be accessed between different domains

  • The internal data of cookies will be carried to the server every time you visit this website. If the cookies are too large, the response speed will be reduced

Use of Cookies

HttpResponse.set_cookie(key, value='', max_age=None, expires = None)

  • Key: the name of the cookie
  • Value: the value of the cookie
  • Max_age: Cookie lifetime
  • expires: specific expiration time
  • When max_age and expires are not specified, this data is invalidated when the browser is closed

Storage example:

  • Add cookie

    # Add a cookie with a key of my_var1, a value of 123 and an expiration time of 1 hour to the browser
    responds = HttpResponse("Added my_var1,The value is 123")
    responds.set_cookie('my_var1', 123, 3600)
    return responds
    
  • Modify cookie

    # Add a cookie with a key of my_var1, a value of 456 and an expiration time of 2 hours to the browser
    responds = HttpResponse("Modified my_var1,The value is 456")
    responds.set_cookie("my_var1", 456, 3600*2)
    return responds
    
  • delete cookie

    HttpResponse.delete_cookie(key)

    Deletes the Cookie for the specified key. If the key does not exist, nothing happens

  • Get cookie

    Obtain the COOKIES data of the client through the dictionary (dict) bound by request.COOKIES

    value = request.COOKIES.get('cookie name ',' default value ')

session definition

session is to open up a space on the server to save important data when the browser interacts with the server

Implementation mode

  • To use session, you need to start the cookie on the browser client and store the sessionid in the cookie
  • Each client can have an independent Session on the server
  • Note: this data will not be shared among different requesters, and it corresponds to the requester one by one

Configure session in settings.py

  1. To installed_ Add to the apps list:

    INSTALLED_APPS = [    
    	# Enable sessions app    
    	'django.contrib.sessions'
    ]
    
  2. Add to the midview list:

    MIDDLEWARE = [    
    	# Enable Session Middleware    	
    	'django.contrib.sessions.middleware.SessionMiddleware'
    ]
    

session can operate in a dictionary like manner on an object of SessionStore type similar to a dictionary

session can store strings, integers, dictionaries, lists, etc

  1. Save the session value to the server

    request.session['KEY'] = VALUE

  2. Gets the value of the session
    value = request.session['KEY']

    value = request.session.get('KEY ', default value)

  3. Delete session

    del request.session['KEY']

Related configuration items in settings.py

  1. SESSION_COOKIE_AGE

    Function: specify the duration of saving sessionid in cookies (2 weeks by default), as follows: SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2

  2. SESSION_EXPIRE_AT_BROWSER_CLOSE = True

    It is set that the session will be invalid as long as the browser is closed (the default is False)

  3. Note: the session data in Django is stored in the database. Before using session, you need to ensure that you have migrate d

Django session

  1. django_session is a single table design; And the data volume of this table continues to increase [the browser intentionally deletes sessionid & expired data is not deleted]
  2. You can execute python3 manage.py clearsessions every night [this command can delete expired session data]

Note: Cookies are stored in the browser and sessions are stored in the server, so sessions are relatively safe

Reference link

Tags: Python Django

Posted on Fri, 15 Oct 2021 00:37:51 -0400 by DavidGS