我使用Django Rest框架构建服务器部分。我有以下型号:
class B:
name_b = models.CharField(max_length=200)
class D:
name_d = models.CharField(max_length=200)
class C:
B_fk = models.ForeignKey(B, related_name='B_id')
D_fk = models.ForeignKey(D, related_name='D_id')
以下是我使用嵌套关系(here)的序列化程序:
class C_Serializer(serializers.ModelSerializer):
class Meta:
model = C
fields = ('D_id',)
class B_Serializer(serializers.ModelSerializer):
B_fk = C_Serializer(many=True)
class Meta:
model = B
fields = ('name_b','B_id',)
我的观点:
class MyView(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticated,)
queryset = B.objects.all()
serializer_class = B_Serializer
我最后有这样的JSON:
[{"name_b": "NAME B", "B_id": [{"D_id": 130},{"D_id": 135},{"D_id": 145},{"D_id": 154}]}]
但我想要
[{"name_b": "NAME B", "B_id":[130, 135, 145, 154]}]
有可能吗?你能帮帮我吗?
提前谢谢!
答案 0 :(得分:0)
您不希望嵌套的序列化程序。默认关系使用PrimaryKeyRelatedField。
class B_Serializer(serializers.ModelSerializer):
B_id = PrimaryKeyRelatedField(many=True, source=B_id)
class Meta:
model = B
fields = ('name_b','B_id',)
请注意,您的模型的related_name似乎是错误的,因为您需要.B_id来访问C实例。