Django Model layer - multi-table operation

A. Create a model

The relationship between the table and the table

    One to one, many-to-many, and publish a book table to table their own relationship Think, think inside the operation, add foreign key constraint and a foreign key constraint without distinction, one of the foreign key constraint the only constraint is to add constraints on many.

  Example: Let's assume the following concepts, fields and relationships

  On the model: the author has a name and age.

  Details of the model: the details of the author's details into the table that contains date of birth, phone number, home address and other information. Is one to one relationship between the author and the author details model model (one-to-one)

  Publisher model: the publisher has a name, city and email.

  Model books: books have a title and date of publication, a book may have multiple authors, an author can write more books, so the relationship between the author and the book is the relationship many to many (many-to-many) ; a book should only be published by a publisher, the publisher and book-to-many relationship (one-to-many).

  Model as follows:

django.db from Import Models # the Create your Models here Wallpaper. class the Author (models.Model): # commonly used inside information into the table models.AutoField = NID (primary_key = True) name = models.CharField (MAX_LENGTH = 32 ) = Age models.IntegerField ()    DEF __str __ (Self):     return # establish one to one relationship with authorDetail, one to one relationship between the two fields to write on any table inside a table can authorDetail = models.OneToOneField (to = " AuthorDetail ", to_field = " NID ", on_delete = models.CASCADE) # is foreignkey + unique, but we do not need to write their own parameters a and orm will automatically help you to spell the name of the field on a _id, database field name is authorDetail_id class AuthorDetail (models.Model): # unusual place inside the table







= Birthday models.DateField () = Telephone models.BigIntegerField () = addr models.CharField (MAX_LENGTH = 64 ) class the Publish (models.Model): name = models.CharField (MAX_LENGTH = 32 ) = models.CharField City (MAX_LENGTH = 32 ) Email = models.EmailField () # table-many relationship, we learn how mysql is established, is not manually create a third table, and then write two fields, each foreign key field in addition to table two many relationships, orm of manytomany automatically help us create the third table, are two ways to build relationships, later learning we do use third table orm created automatically, manually created because third table when we orm operation, many orm statement method between tables on many relationships can not be used # if you want to delete a particular table, you only need to write off the table, and then perform two database synchronization instruction on it, it is automatically deleted. class Book (models.Model): NID = models.AutoField (primary_key = True) = models.CharField title (MAX_LENGTH = 32 ) = publishDatemodels.DateField () =. price models.DecimalField (max_digits =. 5, decimal_places = 2 ) # established with the Publish-to-many relationship, the foreign key field is established in a multi-party, if it is outside the field publish key field, then it is automatically int type = models.ForeignKey publish (to = " publish ", to_field = " NID ", on_delete = models.CASCADE) # ForeignKey which can add a lot of parameters, we all need to learn, slowly, to point to the table, to_field your point field associated with it, do not write this, the default will be automatically associated with the primary key field, on_delete cascading deletes    the field name does not need to be written publish_id, orm when translated foreignkey will automatically give you this fight on a field _id, the field name in a database automatically becomes publish_id # any-many relationship with the Author table, ManyToManyField can be built in one of two models, automatically create the third table, and note that when you look at the book table, you can not see the field because the field is to create meaning the third table, not to create a field of meaning, I can only say this book class there are authors attribute this field models.ManyToManyField = authors (to = ' the Author ',) #Note whether or many-to-many, write to this parameter, the last value is behind the string, otherwise you'll need to watch that you want to associate into the top of the table

 

On Three-many tables created:

Option 1: create your own third table

class Book (models.Model): 
    title = models.CharField (= 32 MAX_LENGTH, the verbose_name = ' title ' ) class the Author (models.Model): name = models.CharField (32-MAX_LENGTH, the verbose_name = ' the author's name ' # create your own third table, respectively, through the foreign key tables of books and class Author_Book (models.Model): the author_id = models.ForeignKey (to = ' the author ' ) = book_id models.ForeignKey (to = ' book ')

Mode 2: Automatically create the third table by MangToManyField

Table foreign key in the Book table Publish point, a property writer insertion-many reference points to attribute Django Author table 

Press = models.ForeignKey (to = ' Publish ' ) 
writer = models.ManyToMany (to = ' Author ' )
to 
    set the table to be associated 

to_field 
    set key fields 

on_delete 
    with ForeignKey field
One field parameter
to 
    set an association table 

to_field 
    field is set to the association table 

related_name 
    reverse operation, the field names use, is used to replace the reverse lookup " table _set ' 

related_query_name 
    connection prefix reverse search operation, use, with to replace the table name 

on_delete 
    when data deletion is associated with the table, the behavior associated with the current table row
Some parameters of many fields
Many to many parameters: 
    to 
        table settings to be associated 

    related_name 
        with ForeignKey field. 

    related_query_name 
        with ForeignKey field. 
    through 
        the use ManyToManyField field, Django will automatically generate a table to manage many to many relationship. 

        But we can also manually create a third table to manage many relationships, then you need         
    to specify the table name the third table through. 

    through_fields 
        set the associated field. 

    db_table 
        default create a third table, the name of the database table.            
Some parameters of many to many fields
Meta information 
    ORM corresponding Meta class which contains another class, and class encapsulates some Meta information database. The main fields are as follows: 
class Author2Book (models.Model): 
    author = models.ForeignKey (to = " the Author " ) 
    Book = models.ForeignKey (to = " Book " )
     class Meta -: 
        unique_together = ( " author " , " Book " ) 

db_table 
    ORM table name in the database app_ default is the class name, the name of the table can be rewritten by db_table. named db_table, = ' book_model ' 

index_together 
    joint index. 

unique_together 
    joint unique index.

ordering 
    specify what the default sort field. 
    Ordering = [ ' pub_date ' ,] 
    only set this property, we query the results can be reverse (), otherwise it is able to sort the results were reversed (order_by () method of the sorted data)
Some sources of information when you create a table settings

Table CRUD relationship between

Many

方式1:
publish_obj = models.Publish.objects.get(id=1)
print(publish_obj)


book_obj = models.Book.objects.create(title='数据',publishDate='2018-5-5',price=200,publish=publish_obj)
print(book_obj)


方式2:
   book_obj = models.Book.objects.create(title='数据',publishDate='2019-5-8'.price=256,publish_id=1)

 

Guess you like

Origin www.cnblogs.com/5kuishoua666/p/11241335.html