Django中是否有可能创建一个查询,该查询将使用两个ForeignKey在表之间创建联接?
为了说明我的意思,假设我在Django中具有以下模型:
class Author(models.Model):
name = models.TextField()
class Publisher(models.Model):
name = models.TextField()
class BooksSold(models.Model):
author = ForeignKey(Author, related_name='books_sold')
publisher = ForeignKey(Publisher, related_name='books_sold')
books_sold = models.IntegerField()
class BooksPrinted(models.Model):
author = ForeignKey(Author, related_name='books_printed')
publisher = ForeignKey(Publisher, related_name='books_printed')
books_printed = models.IntegerField()
我想使用Author和Publisher键联接BooksSold和BooksPrinted表。在sql中将是:
SELECT A.author_id
,A.publisher_id
,A.books_sold
,B.books_printed
FROM table_books_sold A INNER JOIN table_books_printed
ON A.author_id = B.author_id AND
A.publisher_id = B.publisher_id
我当前使用的方法是遍历其中一个通过ForeignKey
加入的模型,并使用另一个ForeignKey
进行过滤,对于此示例:
def get_books_printed(books_sold_model):
return next(b for b in books_sold_model.author.books_printed if b.publisher_id = books_sold_model.publisher_id
books_sold_models = BooksSold.objects.all().prefetch(author__books_printed)
for book_sold_model in books_sold_models:
books_printed = get_books_printed(books_sold_model)
我想知道是否有一种方法可以避免遍历所有实例,直到找到与其他ForeignKey
的匹配项为止