models.py:
from django.db import models # Press class Publisher(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, null=False, unique=True) def __str__(self): return "<Publisher object: {}>".format(self.name) # book class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=64, null=False, unique=True) publisher = models.ForeignKey(to="Publisher") def __str__(self): return "<Book object: {}>".format(self.title) # author class Author(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=16, null=False, unique=True) book = models.ManyToManyField(to="Book") # The ORM automatically generates the third table with many-to-many associative Book tables def __str__(self): return "<Author object: {}>".format(self.name)
book table:
author table:
The third table associated with author and book, author_book table:
Pusher table:
Many-to-many queries:
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models author_obj = models.Author.objects.get(id=2) # Author who gets id 2 ret = author_obj.book.all() # Query all books written by authors with id 2 print(ret)
Operation results:
create():
Create a new object, save the object, add it to the associated object set, and return the newly created object.
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models author_obj = models.Author.objects.get(id=1) # Get the author with id 1 author_obj.book.create(title="<PHP>", publisher_id=2) # Create a book through the author
Operation results:
add():
Adds the specified model object to the associated object set
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models # Add a book with id 2 to the author with id 4 author_obj = models.Author.objects.get(id=4) book_obj = models.Book.objects.get(id=2) author_obj.book.add(book_obj) # You can also add it directly with id # author_obj.book.add(2)
Operation results:
Add more than one
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models # Add more than one book with id greater than 4 to the author with id 3 author_obj = models.Author.objects.get(id=3) book_objs = models.Book.objects.filter(id__gt=4) author_obj.book.add(*book_objs) # Use * to break up the list and pass it in
Operation results:
remove():
Remove the executed model object from the set of associated objects.
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models author_obj = models.Author.objects.get(id=3) book_obj = models.Book.objects.get(title="<PHP>") author_obj.book.remove(book_obj) # Delete the association with title field PHP author_obj.book.remove(5) # Direct deletion
Operation results:
Two books associated with the author of the original id 3 have been deleted
clear():
Clear all objects from the set of associated objects.
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models # Empty all the books of authors with id 4 author_obj = models.Author.objects.get(id=4) author_obj.book.clear()
Operation results:
The content of author_id=4 is completely emptied
set():
Update the associated object of the model object.
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models # Add two books with id 2 and 3 to authors with id 4 author_obj = models.Author.objects.get(id=4) author_obj.book.set([2, 3])
Operation results:
Foreign key supplement:
clear() and remove() methods in foreign keys can only be used when null=True
Book classes in models.py:
# book class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=64, null=False, unique=True) publisher = models.ForeignKey(to="Publisher", null=True) # Set null to True def __str__(self): return "<Book object: {}>".format(self.title)
orm.py:
import os if __name__ == '__main__': # Loading configuration information for Django projects os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings") # Import Django and start the Django project import django django.setup() from app01 import models # Empty the books in the publishing house with id 2 publisher_obj = models.Publisher.objects.get(id=2) publisher_obj.book_set.clear()
Operation results:
Pusher_id is changed from 2 to 0