Python Full Stack Web (Django Framework, Background Management, ORM Relationships)

Keywords: Linux Attribute SQL Django Database

F query and Q query:
    F()
Get the value of a field in its execution
F("field name")
Increase everyone's age by 10
        form django.db.models import F
        Author.objects.all().update(age=F("age")+10)

def doF_views(request):
  Author.objects.all().update(age=F('age')+10)
  return redirect('/07-queryall')

    Q()
The or operation can be completed in the query condition
Q (Conditions) | Q (Conditions)
Query all people whose id is 1 or age is 48
        form django.db.models import Q
        Author.objects.filter(Q(id=1)|Q(age=48))

  authors = Author.objects.filter(Q(age=30|Q(id__gt=20)))

Native database operation method:
Query:
Function: raw(sql)
            Entry.objects.raw(sql)
Return value: QuerySet
Add, delete and modify:
        from django.db import connection
        with connection.cursor() as cursor
            sql = "delete from ..."
            cursor.execute(sql)
            return ""

def raw_views(request):
  sql = "select * from index_author where age>45"
  authors = Author.objects.raw(sql)
  for au in authors:
    print(au.name,au.age,au.email)
  return HttpResponse("Query OK")

Use background management models
Create a Background Administrator
      ./manage.py createsuperuser
Username: Enter the username if you do not write the default system name
email Address: E-mail
Password: Password
Password(agian): duplicate passwords
Basic management:
Register data to be managed in admin.py of the application
        1.admin.py
Register the model classes to be managed. Only the model classes registered here are allowed to be managed
2. Registration models
            from .models import *
            admin.site.register(Entry)
Define the presentation form through the internal class meta of the models class
        class Author(models.Model):
            ...
            ...
            class Meta:
                db_table
Specify the name of the entity class mapped to the table
(This property will be synchronized to the database when it is set)
                verbose_name
Define the name (singular) of the entity class that appears in admin
                verbose_name_plural
Define the name of the entity class displayed in admin (plural)

#Create Author's entity class
#1.name - name (CharField - > varchar)
#2.age-age (IntegerField-> int)
#3.email Field - > varchar
class Author(models.Model):
  name = models.CharField(max_length=30,verbose_name='Full name')
  age = models.IntegerField(verbose_name='Age')
  email = models.EmailField(null=True,verbose_name='mail')
  #Represents the user's activation status: True, indicates activated, False, indicates inactive
  #Since it is a new column, it must be given a default value or allowed to be null.
  #Because BooleanField is not allowed to be empty by default, the default value is added here.
  isActive = models.BooleanField(default=True,verbose_name='Activate user')
  #Add a field to represent the user's avatar, which can be uploaded
  picture = models.ImageField(upload_to="static/upload",null=True,verbose_name='Head portrait')

  # Rewrite _str_ to define the string representation of the object
  def __str__(self):
    return self.name

  #Adding an internal class Meta to define its presentation
  class Meta:
    #1. Modify the table name to author
    db_table = 'author'
    #2. Name to be displayed when specifying background management
    verbose_name = 'author'
    verbose_name_plural = verbose_name
    #3. Specify sorting rules
    ordering = ['-age']
  def __repr__(self):
    return "<Author:%r>" % self.name

Senior Management:
Create and register senior management classes in admin.py
Define the EntryAdmin class to inherit admin.ModelAdmin
        class AuthorAdmin(admin.ModelAdmin):
            pass
Registration of senior management classes
        admin.site.register(Entry, EntryAdmin)

Allow adding attributes to Entry Admin
        list_display
Define the fields displayed on the list page
Value:
Tuples or lists of attribute names
        list_display_links
Fields defined on the list page can also be linked to the details page
Value:
Ibid.
The values here must appear in list_display
        list_editable
Define the fields that are allowed to be modified in the list page
Value:
Ibid.
Must appear in list_display but not in list_display_links
        search_fields
Add fields that allow search
Take the same value as above
        list_filter
Adding filters to the right test of list pages to achieve rapid screening
        date_hierarchy
Increase the time selector at the top of the list page
Column names of DateField or DateTime Field
        fields
In the Details page, specify which fields to display and in what order
Value:
List or tuple of attribute names
        fieldsets
Grouping fields on the Details page
fieldsets and fields cannot coexist
Value:
                fieldsets = [
# Group 1
(Grouping name){
Field: ("Attribute 1", "Attribute 2")
                        "classes": ("collapse")
                    }),
# Group 2
                    (),

                ]

from django.contrib import admin
from .models import *

#Declare the Advanced Management Class
class AuthorAdmin(admin.ModelAdmin):
  #Specify the fields to be displayed on the list page
  list_display = ('name','age','email')
  #Specify fields that can be connected to the details page
  list_display_links = ('name','email')
  #Specify fields that are allowed to be modified in the list page
  list_editable = ('age',)
  #Search fields with specified criteria
  search_fields = ('name','email')
  #Specify the right filter
  list_filter=('name',)
  #Specify the fields to be displayed and the order to be displayed
  # fields = ('name','isActive','email')
  #Specify the field grouping to be displayed
  fieldsets = (
    #Group 1
    ('Essential information',{
      'fields':('name','email'),
    }),
    #Group 2
    ('optional information',{
      'fields':('age','isActive','picture'),
      'classes':('collapse',),
    })
  )


class BookAdmin(admin.ModelAdmin):
  #Designated time selector
  date_hierarchy = "publicate_date"


class PublisherAdmin(admin.ModelAdmin):
  list_display = ('name','address','city','website')
  list_editable = ('address','city')
  list_filter = ('address','city')
  search_fields = ('name','website')
  fieldsets = (
    ('Basic options',{
      'fields':('name','address','city'),
    }),
    (
      'Advanced options',{
        'fields':('country','website'),
        'classes':('collapse',)
      }
    )
  )


# Register your models here.
# Register Advanced Management Class
admin.site.register(Author,AuthorAdmin)
admin.site.register(Publisher,PublisherAdmin)
admin.site.register(Book,BookAdmin)
# Register General Management Class
admin.site.register(Wife)


Relational mapping:
One-to-one mapping
Grammar:
Increase in any of the associated linked classes
Attribute = models.OneToOneField(Entry)

            class Author(models.Model):
                ....

            class Wife(models.Model);
                ....
# Add a one-to-one reference to Author
                author = models.OneToOneField(Author)
# Generate a foreign key column in the database in the wife table and refer to the primary key from the author table
# An implicit attribute called wife is also added to the Author model.

  #Implementing one-to-one mapping by referring to Author
  author = models.OneToOneField(Author,verbose_name='Husband')

Query:
Forward inquiry:
Connected data can be obtained directly through association attributes
Find author through wife
                wife = Wife.objects.get(id=1)
                author = wife.author
Reverse query:
Query by inverting attributes
Find wife by author
                author = Author.objects.get(id=1)
# The property of the reverse reference is the lowercase of the model class
                wife = author.wife

  #Forward query
  wife = Wife.objects.get(id=1)
  wife_author = wife.author
  #inverse query
  author = Author.objects.get(id=1)
  author_wife = author.wife
  return render(request,'14-oto.html',locals())

One-to-many mapping:
Grammar:
Reference to the "one" model in the "many" model
Attribute = models.ForeignKey(Entry)
            class Publisher(models.Model):
                ....

            class Book(models.Model):
                ....

                publisher = modelsForeignKey(Publisher)

  #Increase the reference to Publisher (1:M)
  publisher = models.ForeignKey(Publisher,null=True)

Query:
Forward inquiry:
                book = Book.objects.get(id=1)
                publisher = book.publisher
Reverse query:
By default, django adds the book_set attribute to the publisher to represent the corresponding query objects for all books
                publisher = Publisher.objects.get(id=1)
                publisher = publisher.book_set.all()


def otm_views(request):
  # Forward Query: Publisher is queried by Book and the corresponding publisher for each book is displayed in 15-otm.html
  books = Book.objects.all()
  # inverse query
  pub = Publisher.objects.get(id=1)
  pub_books = pub.book_set.all()
  return render(request,'15-otm.html',locals())

Multi-to-many mapping:
Grammar:
Increase in any class associated
Attribute = models.ManyToManyField(Entry)
            class Author(models.Model):
                ....

            class Book(models.Model):
                ....

                authors = models.ManyToManyField(Author)

  #Increase the reference to Author (M:N)
  authors = models.ManyToManyField(Author)

Query:
Forward inquiry;
Query Author through Book
authors attributes only provide query references to associated tables and also need to use all() values() and other methods to obtain real data


def mtm_views(request):
  #Forward Query: Query authors through book
  book = Book.objects.get(id=1)
  authors = book.authors.all()
  #Reverse Query: Query book through author
  author = Author.objects.get(id=2)
  books = author.book_set.all()
  return render(request,'16-mtm.html',locals())


Posted by anxiety on Wed, 15 May 2019 03:19:36 -0700