Database table relationships: Three-in-many ways

1, the first django orm automatically help us in the creation of the table to create table relationships

from django.db import models

# Create your models here.

# Create a book table
class Book(models.Model):
    name=models.CharField(max_length=32)
    # The first way, the system automatically creates a table to help us book author and relationship table
    authors=models.ManyToManyField(to='Author')

Create a table of #
class Author(models.Model):
    name=models.CharField(max_length=32)

 

Book_authors table is automatically created out of the author and book tables for association

 

 

 

2. Create a table (third table) the second pure manual

 

from django.db import models

# Create your models here.

# Create a book table
class Book(models.Model):
    name=models.CharField(max_length=32)
    # # The first way, the system automatically creates a table to help us book author and relationship table
    # authors=models.ManyToManyField(to='Author')

Create a table of #
class Author(models.Model):
    name=models.CharField(max_length=32)

class Book2Author(models.Model):
    book=models.ForeignKey(to='Book')
    author=models.ForeignKey(to='Author')
    info=models.CharField(max_length=32)

  Benefits manually create relational tables is that you can create custom fields in relational tables; drawback is that you can not use orm

 

 

3, the third semi-automatic create a third table (scalable high surname, in line with orm inquiry)

from django.db import models

# Create your models here.

# Create a book table
class Book(models.Model):
    name=models.CharField(max_length=32)
    # # The first way, the system automatically creates a table to help us book author and relationship table
    # authors=models.ManyToManyField(to='Author')
    authors=models.ManyToManyField(to='Author',through='Book2Author',through_fields=('book','author'))

Create a table of #
class Author(models.Model):
    name=models.CharField(max_length=32)
   # books=models.ManyToManyField(to='Book',through='Book2Author',through_fields=('author','book'))
class Book2Author(models.Model): book=models.ForeignKey(to='Book') author=models.ForeignKey(to='Author') info=models.CharField(max_length=32)

  Semiautomatic need to create relational tables, you can customize fields, you can query in line orm

By orm query data:

from django.test import TestCase

# Create your tests here.
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test01.settings")
    import django
    django.setup()
    from app01 import models


    # Query corresponding author books
    models.Book.objects.filter = RES (= PK. 1) .values ( 'authors__name')    # underlined based
     print (res)

    book_obj=models.Book.objects.filter(pk=1).first()
    res=book_obj.authors.all()
    print(res)

 

Front and rear ends data transmission encoding format contentType

urlencoded

  A data format: name = jason & password = 555

  Back-end data acquisition: request.POST

  Note: django urlencoded coded data analyzer will automatically placed request.POST

formdat to:

  Encoding format file transfer sheet form

  Back-end data acquisition file formats: request.FILES

  Back-end data acquisition ordinary key-value pairs: request.POST

application/json

  ajax json format data transmission

  Note that: encoding data format to keep up

 

ajax

  1, the front end of ways in which requests can be sent toward the rear end

    Browser window to manually enter the URL get request

    href attribute request to get a tag

    form form get / post request (get request default)

    ajax get / post request

 

  2, ajax features:

    Asynchronous submitted

    Partial refresh

  3, ajax basic grammar

    Address submitted (url)

    Submission of the (type)

    Submitted data (data)    

    Callback function (Success)
    $ ( '# d1') the Click (function () {.
        $ .Ajax ({
          // address submitted
          url: '/ index /',
          the way // submission
          of the type: 'POST',
          // submitted data
          data: { 'name': 'Jason', 'password': '123'},
          // callback
          success: function (data) {// data is submitted asynchronously received results returned
          Alert (data)
          }
        })
      })

  4, ajax default transmission data encoding format is urlencoded

  5, the front end of the back-end data transmission, data is what format they should tell others what format (encoded data to one correspondence)

  Data transfer format ajax json

  $ ( '# d1') the Click (function () {.
      $ .ajax ({
        url: '', // url parameter can not write, the default is to open the current page address
        of the type: 'POST',
        contentType: 'the Application / JSON ',
        Data: the JSON.stringify ({' name ':' Jason ',' Hobby ':' Study '}),
        Success: function (Data) {
          {#alert (Data)} #
          {# $ (' # I3 ') .val (Data) #}
        }
      })
    });

  Ajax transfer file
    $ ('. # D1 ') the Click (function () {
      the let FormData the FormData new new = ();
      // can not pass the FormData target document also Common key can be transferred to
      formdata.append ( 'name', 'Jason');
      // Get input block storage file
      // $ ( '# i1') [0].files[0]
      formdata.append('myfile',$('#i1')[0].files[0]);
      .ajax $ ({
        url: '',
        of the type: 'POST',
        the Data: FormData,
        // ajax to send the file you need to modify two fixed parameters
        processData: false, // tell the browser not handle my data
        contentType: false, // Do not use any encoding, to use my own formdata encoding format, Django can automatically identify objects change formdata
        // callback
        Success: function (Data) {
        Alert (Data)
        }
       })
      });
  form forms with ajax similarities and differences
  1.form form does not support asynchronous submit partial refresh
  2.form form transport json format data do not support
  3.form form with ajax default encoding format for transmitting data is urlencoded

 

Bulk insert data
  L = []
  for I in Range (10000):
  l.append (models.Book2 (name = '% s of the book'% I))
  models.Book2.objects.bulk_create (L) Bulk insert data #



  added: <li> <a href="?page=1"> 1 </a> </ li> # automatically complete the current path

  custom pager
    page rendering are typically singular 1,3,5,7, 9, symbol Chinese people's aesthetic standards


    need to be perfected
      1. plus first and last page
      2. page number should be fixed


    using a custom finisher
    backend:
      book_list = models.Book2.objects.all ()
      # data total number of
      ALL_COUNT are book_list.count = ()
      # this page
      current_page = request.GET.get ( 'page',. 1)
      # example a tab object
      page_obj = my_page.Pagination (current_page = current_page, ALL_COUNT are = ALL_COUNT are)
      # of total slice the data
      page_queryset = book_list [page_obj.start: page_obj.end]

    front end:
      {{page_obj.page_html |}} # Safe render help you with that pager style bootstrap

Guess you like

Origin www.cnblogs.com/yangzhaon/p/11025737.html