Django Filter Query Foreign Key

前端 未结 1 919
独厮守ぢ
独厮守ぢ 2021-01-30 01:51

I\'m struggling getting the right query for my project. Here is an example or my model :

from django.db import models

class Publisher(models.Model):
    name =          


        
相关标签:
1条回答
  • 2021-01-30 02:30

    If you want to get Publishers, you have to start with Publisher. That means you have to query through the Book → Publisher relation backwards. Here's what the docs say about it:

    Lookups that span relationships

    To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want

    ...

    To refer to a “reverse” relationship, just use the lowercase name of the model.

    The query:

    Publisher.objects.filter(book__title__startswith='hello')
    
    0 讨论(0)
提交回复
热议问题