Get grandchildren of an object with django

一世执手 提交于 2019-12-01 09:22:37

问题


I'm building a webapp with django with the following models:

class Business(models.Model):
    ...

class Branch(models.Model):
    business = models.ForeignKey(Business)
    ...

class Event(models.Model):
    branch = models.ForeignKey(Branch)

My questions is how can I get all events by their business (not their branch), and if it possible to do so in a DB query.

Thanks!


回答1:


Django querysets allow you to use the "__" notation to access relationships. You can take it to any depth and read more about it here.

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. 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.

Any of the following should work in your case:

Event.objects.filter(branch__business=<business>)
Event.objects.filter(branch__business_id=<business-id>)
Event.objects.filter(branch__business__id=<business-id>)
# if business had a name field you could also use
Event.objects.filter(branch__business__name=name-of-business)


来源:https://stackoverflow.com/questions/41381880/get-grandchildren-of-an-object-with-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!