代码之家  ›  专栏  ›  技术社区  ›  Cooper

如何在预取模型上选择“相关”?

  •  0
  • Cooper  · 技术社区  · 6 年前

    是否可以选择与您预取的模型的外键相关的模型?

    一组模型示例:

    class Book(models.Model):
        title = models.CharField(max_length=50)
        author = models.ForeignKey('Author', related_name='books')
        publisher = models.ForeignKey('Publisher')
    
    class Author(models.Model):
        name = models.CharField(max_length=50)
        type = models.IntegerField() # choices= omitted for brevity
    
    class Publisher(models.Model):
        name = models.CharField(max_length=50)
    

    然后查询:

    authors = Author.objects.filter(type=10)
    authors = authors.prefetch_related('books')
    
    # I tried both of these (but not at the same time):
    authors = authors.select_related('publisher')  # doesn't work
    authors = authors.select_related('books__publisher')  # also doesn't work
    

    在这两种情况下,我都会得到一个字段错误:

    Invalid field name(s) given in select_related
    

    这是有意义的,因为出版商和图书出版商都不与启动模型(作者)关联。但我不知道如何表明我想在预取模型(书)上执行与选择相关的操作,而不是开始模型(作者)。

    我确实看过 Prefetch objects 但是我看不出这些会有什么帮助。

    1 回复  |  直到 6 年前
        1
  •  2
  •   neverwalkaloner    6 年前

    prefetch

    authors = Author.objects.filter(type=10)
    authors = authors.prefetch_related('books', 'books__publisher')