Django Database Operations-additions and deletions-many-to-many relationships and one-to-many (foreign key) relationshipsoriginal August 29, 2012 14:56:33
- Label:
- Django/
- Database
- Class/
- Email/
- Publishing
One or one-to-many (foreign key)
Example: One author corresponds to multiple books, one book only one author
Model Code:
[Python]View Plain Copy
- Class person (models. Model);
- Name = models. Charfield (' author name ', max_length=)
- Age = Models. Integerfield (' author age ')
- Class book (Models. Model):
- Person = models. ForeignKey (person, related_name=' Person_book ')
- title = models. Charfield (' book name ', max_length=)
- Pubtime = models. Datefield (' publication Time ')
(i) Get the object method:
1. Obtaining books from the author
[python] view plain copy
- person = Person.objects.fiter (your condition)
- Book = Person.book_set.all ()
2. Get authors from books
[python] view plain copy
- p = Book.person
Two, many-to-many
Example: One author corresponds to multiple books, one book has multiple authors
Model Code:
[Python]View Plain Copy
- Class Author (models. Model):
- First_Name = models. Charfield (max_length=)
- Last_Name = models. Charfield (max_length=)
- email = models. Emailfield ()
- Class book (Models. Model):
- title = models. Charfield (max_length=)
- Authors = models. Manytomanyfield (Author)
(i) Get the object method:
1. Get authors from books
[python] view plain copy
- b = Book.objects.get (id=)
- B.authors.all ()
- B.authors.filter (first_name=' Adam ')
2. Obtaining books from the author
[python] view plain copy
- A = Author.objects.get (id=1)
- A.book_set.all ()
(ii) Add object method:
[Python]View Plain Copy
- A = Author.objects.get (id=1)
- b = Book.objects.get (id=)
- B.authors.add (a)
(iii) Delete Object object methods:
[Python]View Plain Copy
- A = Author.objects.get (id=1)
- b = Book.objects.get (id=)
- B.authors.remove (a) or B.authors.filter (id=1). Delete ()
Django Database Operations-additions and deletions-many-to-many relationships and one-to-many (foreign key) relationships