问题
I have a model with a self referential field called parent. Model:
class Zone(BaseModel):
name = models.CharField(max_length=200)
parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='children')
def __unicode__(self):
return self.name
Serializer:
class ZoneSerializer(ModelSerializer):
parent = PrimaryKeyRelatedField(many=False, queryset=Zone.objects.all())
parent_disp = StringRelatedField(many=False, source="parent")
class Meta:
model = Zone
fields = ('id', 'name', 'parent', 'parent_disp')
Now I want to serialize the parent of the zone and its parent and its parent till parent is none. I found recursive serialization methods for children but not for parent. How can I do this?
回答1:
Try use SerializerMethodField here:
def get_parent(self, obj):
# query what your want here.
I'm not sure D-R-F has build-in methods for this, but you can use query to get what you want in this method.
回答2:
Ok, I got it working like that.
class ZoneSerializer(ModelSerializer):
parent = SerializerMethodField()
class Meta:
model = Zone
fields = ('id', 'name', 'project', 'parent',)
def get_parent(self, obj):
if obj.parent is not None:
return ZoneSerializer(obj.parent).data
else:
return None
来源:https://stackoverflow.com/questions/39104575/django-rest-framework-recursive-nested-parent-serialization