【问题标题】:Additional Foreign Key Query in DjangoDjango 中的附加外键查询
【发布时间】:2021-06-03 09:54:05
【问题描述】:

我是 django 的新手,正在阅读有关 select_related 的信息。我知道每当访问外键时,django 都会执行一个附加查询。但是当我检查DEBUG 登录我的代码时,无论是否访问外键,django 似乎都会执行two 查询。有人可以解释这种行为吗?

class Person(models.Model):
    # ...
    name = models.CharField(max_length=250)

class Book(models.Model):
    # ...
    author = models.ForeignKey(Person, on_delete=models.CASCADE)

根据文档

# Without select_related()...
b = Book.objects.get(id=4)  # Executes a query.
p = b.author         #Executes a query.

但是使用 get() 它会执行两个查询

b = Book.objects.get(id=4)  # Executes two queries (one for books one for author).

【问题讨论】:

    标签: django django-models django-queryset django-select-related


    【解决方案1】:

    首先需要调用select select_related:

    ids = [1,2,3,4]
    query = Book.objects.filter(id__in=ids).select_related('author')
    

    请注意,我使用的是 filter 方法而不是 get 方法。

    原因是select/prefetch相关的get方法不起作用。

    如果您仍然只想要一个与选择相关的对象,您应该这样做:

    book = Book.objects.filter(id=4).select_related('author')[0]
    author = book.author
    

    或者做:

    book = Book.objects.select_related('author').get(id=4)
    author = book.author
    

    如果您想为多个对象执行此操作并获取所有作者:

    ids = [1,2,3,4]
    query = Book.objects.filter(id__in=ids).select_related('author')
    authors_in_query = [book.author for book in query]
    

    【讨论】:

      猜你喜欢
      • 2013-09-27
      • 2011-02-01
      • 2018-09-01
      • 2015-03-09
      • 1970-01-01
      • 2011-01-02
      • 2012-05-22
      • 2011-10-20
      • 2020-08-26
      相关资源
      最近更新 更多