Create a table
# -Many relationship between the author and the book class Author (models.Model): '' ' On the Table ' '' NID = models.AutoField (primary_key = True) name = models.CharField (verbose_name = ' Author ' , 32 = max_length ) # the first way to create ManyToManyField directly in the field of the table (ORM will automatically help us create the third table recommend this approach) author2books = models.ManyToManyField (to = ' Books ' ) class Books (Models. Model): '' ' title of the book ' '' NID = models.AutoField (primary_key = True) titleModels.CharField = (the verbose_name = ' book name ' , MAX_LENGTH = 32 ) PID = models.ForeignKey (= the verbose_name ' Press ID ' , to = ' Press ' , to_field = ' NID ' , on_delete = models.CASCADE) # of create a third table two clock manually # class Books2Author (models.Model): # '' ' # book of correspondence table # ' '' # NID = models.AutoField (primary_key = True) # the AID = models.ForeignKey (verbose_name = 'author ID', to = 'author' , to_field = 'nid') # bid = models.ForeignKey(verbose_name='书籍ID',to='Books',to_field='nid')
Adding data
# Editorial writers DEF edit_author (Request): # Get Authors ID the above mentioned id = request.GET.get ( ' the above mentioned id ' ) # get all the books books_lst = models.Books.objects.all () # according to the authors of the object ID to get author_info = models.Author.objects.filter (PK = the above mentioned id) .first () IF request.method == ' POST ' : # retrieve a front passed over the name of the new name = request.POST.get ( ' name ' ) # get the front end books pass over the book_lst = request.POST.getlist ( ' Books' ) # Under the new name, update the current name author_info.name = name # save data author_info.save () # the SET will remove the current method of all original books, and then insert the tip passes over a list of books (parameter list type) author_info.author2books.set (book_lst) # the Add method will add to the front passing over books and books of correspondence table. If duplicate records are given insert (parameters for individual elements, can be inserted into a plurality of) # author_info.author2books.add (* book_lst) return the redirect ( ' / author_lst / ' ) return the render (Request, ' edit_author.html ' , { ' books_lst ' : books_lst, ' author_info':author_info})