Get grandchildren of an object with django

后端 未结 1 1462
慢半拍i
慢半拍i 2021-01-15 05:29

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

class Business(models.Model):
    ...

class Branch(models.Model):
    business = models.Foreig         


        
相关标签:
1条回答
  • 2021-01-15 06:05

    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)
    
    0 讨论(0)
提交回复
热议问题