from django.db import models class Publisher(models.Model): name = models.CharField(max_length=32, verbose_name='出版社名称') def __str__(self): return self.name class Meta: verbose_name = "name" verbose_name_plural = verbose_name class Book(models.Model): name = models.CharField(max_length=32, verbose_name='书名') pub = models.ForeignKey('Publisher', on_delete=models.CASCADE,related_name='books', related_query_name='book') def __str__(self): return self.name class Meta: verbose_name = 'name' verbose_name_plural = verbose_name
######################## # 基于对象的查询 book_obj = models.Book.objects.get(pk=1) # 正向查询 book_obj.pub # 所关联的对象 book_obj.pub_id # 所关联的对象id # 反向查询 pub_obj = models.Publisher.objects.get(pk=1) # 不指定related_name 使用 类名下列_set pub_obj.book_set # 关系管理对象 pub_obj.book_set.all() # 所关联的所有的书籍对象 # 指定 related_name = 'books' pub_obj.books.all() # 基于字段的查询 ret = models.Book.objects.filter(name='xxxxxxxx') ret = models.Book.objects.filter(pub__name='出版社') ret = models.Publisher.objects.filter(name='出版社') # 不指定 related_name ret = models.Publisher.objects.filter(book__name='xxxxxxx') # 指定 related_name='books' ret = models.Publisher.objects.filter(books__name='xxxxxxx') # 指定related_query_name='xxx' ret = models.Publisher.objects.filter(xxx__name='xxxxx')