python - Get all "grand"-Children of a given Model -
im trying learn python/django @ moment , came across following problem. let's have 3 models:
model category(models.model) name = models.charfield(max_length64) model subcategory(models.model) category = models.foreignkey(category) name = models.charfield(max_length64) model animal(models.model) subcategory = models.foreignkey(subcategory) name = models.charfield(max_length64)
now, example, if searches category, want have animals in of subcategories of given main category. ( hope not complicated)
so question efficient way this?
thanks in advance!
you can query like:
animals = animal.objects.filter(subcategory__category__id=category_id)
or, if have access category object,
animals = animal.objects.filter(subcategory__category=category)
please note model object definition class <classname>
, not model <classname>
example: model animal
should class animal
Comments
Post a Comment