How to build witt django-mptt a query joining to any descendant of mptt hierarchy element? -
i want build django-mptt hierarchy of vegetables classes (fruit -> berries -> strawberry -> douglas strawberry) being last level variety. retailer stocks related leaf level, variety (golden apple, douglas strawberry...), consumers used ask upper level (apple, pear, orange, lettuce...). useful query wold "select retailers having stock product of 'strawberry' or children.
let me illustrate example code:
class vegetable(mpttmodel) : name = textfield(...) group = treeforeignkey('self', related_name='subgroups', null=true, default=none) class mpttmeta: parent_attr = 'group' def getretailers(self) : # here missing code class retailer(model) : name = textfield(...) vegetables = manytomany(vegetable, null=true) fruits = vegetable(name='fruit') pears = vegetable(name='pear', group=fruits) apples = vegetable(name='apple', group=fruits) goldenapples = vegetable(name='golden apple', group=apples) royalapples = vegetable(name='royal apple', group=apples) o in fruits, pears, apples, goldenapples, royalapples : o.save() toni = retailer(name='toni') pere = retailer(name='pere') benet = retailer(name='benet') mall = retailer(name='citymall') o in toni, pere, benet, mall : o.save() toni.vegetables.add(pears) pere.vegetables.add(goldenapple) pere.vegetables.add(royalapple) benet.vegetables.add(goldenapple) mall.vegetables.add(apples) # following query set should return pere, benet , citymall not toni. vegetable.get(name='apple').getretailers()
so how should build such query django api?
you can query set of mpttmodel
descendants get_descendants
:
creates
queryset
containing descendants of model instance, in tree order.if
include_self
true
,queryset
include model instance.
so particular vegetable:
# retailers where... retailers = retailers.objects.filter( # ...one or more of it's vegetables in list of # things descendant of 'vegetable', including itself. vegetables__in=vegetable.get_descendants(include_self=true) ).distinct()
Comments
Post a Comment