Many table structure
ForeignKey - foreign key to another table associated
class Book (models.Model): title = models.CharField (MAX_LENGTH = 32 ) Pub = models.ForeignKey ( ' Publisher ' , on_delete = models.CASCADE) # foreign key - associated table other table
Inquire
= models.Book.objects.all all_books () # get all data Print (all_books) for Book in all_books: Print (Book) # obtain a data object Print (book.pk) # primary key data object ID Print (Book. title) # value in the title field of the data object Print (book.pub, type (book.pub)) # object is a foreign key Print (book.pub_id, type (book.pub_id)) # object ID foreign key
New
DEF book_add (Request): IF request.method == ' the POST ' : # determination request method title request.POST.get = ( ' title ' ) # 'title' attribute value acquired value (typing) by the input frame name = = request.POST.get the pub_id ( ' the pub_id ' ) # above # models.Book.objects.create (title = title, Pub = models.Publisher.objects.get (= the pub_id PK)) models.Book.objects.create ( title = title, the pub_id = the pub_id) # synchronized to the database (database field = value obtained) return the redirect ( ' / book_list / ' ) # Redirect, jump page
delete
DEF book_del (Request): pk = request.GET.get ( ' pk ' ) # Get value corresponding to the value of the url pk models.Book.objects.filter (pk = pk) .Delete () # Comparative Book table pk Get value pk value of url, delete the same return the redirect ( ' / book_list / ' )
edit
DEF book_edit (Request): pk = request.GET.get ( ' pk ' ) # obtain pk value corresponding to the GET request transmitted book_obj models.Book.objects.filter = (pk = pk) .first () # acquires values corresponding pk data objects IF request.method == ' the POST ' : title = request.POST.get ( ' title ' ) # INPUT box name = 'title' attribute value corresponding to the value of the pub_id = request.POST.get ( ' the pub_id ' ) book_obj.title = title # modify the value of the book table data object pub_id = book_obj.pub_id # acquired by pub_id value to the value of the option, and to modify the values in the table book, (pub_id foreign key pk correspond to a value corresponding to the table data publisher) book_obj.save () # submit data return the redirect ( ' / book_list / ' )