Set max recursion depth when serializing Django model with foreign key to JSON

I have a Django model built for Google App Engine,

Model A():
  propA = ReferenceProperty(B)

Model B():
  propB = ReferenceProperty(C)

Model C():
  propC = ReferenceProperty(B)

      

I wrote a custom Django serializer that will extract the data for the ReferenceProperty (s) and serialize it against the original model.

The problem occurs when I try to serialize an instance of Model A . My custom serializer will try to get propA that contains a reference to Model C so that the serializer will retrieve Model C that contains a reference to Model B and the recursion goes on and on. Is there a way to stop recursion after word depth 2 ??

My serializer is a custom version of the link text

PS: I'm willing to post my code if needed. I am not currently attaching the code as I am not on my development machine.

Thank you,
Arun Shanker Prasad.

0


a source to share


3 answers


Just change your functions to accept a "depth" argument. Every time you execute the ReferenceProperty, call the function with a depth equal to less than the depth that was passed. If the function is called with depth == 0, return None or any other placeholder value in your case.



+2


a source


Why don't you just do the recursion? Any recursive operation must have a base block otherwise it will go on forever as your problem points out.



0


a source


I am trying to find a serializer that works with Google App Engine and follows relationships. Would it be possible to post the modified code you used to do this?

0


a source







All Articles