我希望使用 Django 查询集以最佳方式解决这个问题。
每个图书馆只能拥有一本书。 多个图书馆可以有同一本书的多个实例(即:Library1 可以有一个“Girl with the Dragon Tattoo”的实例,Library4 可以有另一个“Girl with the Dragon Tattoo”的实例)
Book(models.Model):
name = models.CharField(max_length=30)
Library(models.Model):
book = models.ForeignKey(Book) # multiple libraries have the book
city = models.CharField(max_length=50)
那么我如何找到一本在少于 3 个图书馆中的书呢?
最佳答案
使用注释
和计数
。
Book.objects.annotate(n_libraries=Count('library')).filter(n_libraries__lt=3)
关于mysql - Django 查询集复杂查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404787/