想象一下有三个 Django 模型:
ActualMessage: "A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles."
BytePositionInLine: null
ClassName: "System.Text.Json.JsonException"
Data: null
ExceptionMethod: null
HResult: -2146233088
HelpURL: null
InnerException: null
LineNumber: null
Message: "A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles."
Path: "$.requestorRoles.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.Claims.Subject.AuthenticationType"
RemoteStackIndex: 0
RemoteStackTraceString: null
Source: "System.Text.Json"
StackTraceString: " at System.Text.Json.ThrowHelper.ThrowJsonExcep
WatsonBuckets: null
我想为 class A:
Susu = models.CharField()
# props...
class B:
a = models.ForeignKey(A)
Bar = models.CharField()
# props...
class C:
b = models.ForeignKey(B)
c_prop
# props...
对象编写一个序列化程序,以便将它们表示为
C
即{
"c_prop": "Foo",
"b" : {
"Bar": "Agu"
},
"a" : {
"Susu", "Jaja"
}
}
类的外键表示在与 B
对象相同的嵌套级别(而不是“内”B)
我有这些序列化程序:
B
答案 0 :(得分:1)
你可以这样使用SerializerMethodField
a = serializers.SerializerMethodField()
def get_a(self,obj):
a = A.objects.filter(b__c=obj)
return ASerializer(a, many=True).data