2

I have django model which consist of parent child relationship filed

I want to print parent child relation objects which will seperated by dot(.) like, ParentName.SubparentName.ChildName.subchildName.. etc...

How can i achieve this using recursive technique.

 class SomeModel(models.Model)
      parent = models.ForeignKey('self', related_name=childrens).
0

2 Answers 2

2
def print_obj(obj, prefix=''):
    sys.stdout.write('%s%s' % (prefix, obj))
    if obj.child:
        print_obj(obj, '.')

But i think that cycle would be better:

def print_obj(obj):
    sys.stdout.write(str(obj))
    obj = obj.child
    while obj:
        sys.stdout.write('.%s' % obj)
        obj = obj.child
0

Please check this documentation in this example they mention how to call parent child relationship with poll.choice_set

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.