gpt4 book ai didi

json - 如何获取主键相关字段嵌套序列化程序 django rest 框架的所有值

转载 作者:行者123 更新时间:2023-12-04 12:06:42 25 4
gpt4 key购买 nike

我有以下型号:

class SearchCity(models.Model):
city = models.CharField(max_length=200)

class SearchNeighborhood(models.Model):
city = models.ForeignKey(SearchCity, on_delete=models.CASCADE)
neighborhood = models.CharField(max_length=200)

然后是以下嵌套序列化程序:
class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer):
searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

class Meta:
model = SearchCity
fields = ('city','searchneighborhood_set')
read_only_fields =('city', 'searchneighborhood_set')

与 View 配对:
class CityNeighborhoodView(ListAPIView):
queryset = SearchCity.objects.all()
serializer_class = CityNeighborhoodReadOnlySerializer

当我进行 api 调用时,我得到了这个:
city: "Chicago"
searchneighborhood_set:
0: 5
1: 4
2: 3
city: "New York"
searchneighborhood_set:
0: 8
1: 7
2: 6

我只是获取相关对象的主键。哪个好,我需要,但我也想要 neighborhood名字我怎么得到?

编辑:

这个问题可能会带来一些启发。他们没有使用与主键相关的序列化程序,所以我的问题是(如果这当然有效,那么与主键相关的序列化程序的意义是什么?

Django Rest Framework nested serializer not showing related data

最佳答案

答案是不使用 primarykeyrelatedserializer而是用于序列化的序列化程序 Searchneighborhood对象。

我改变了这个:

class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer):
searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

class Meta:
model = SearchCity
fields = ('city','searchneighborhood_set')
read_only_fields =('city', 'searchneighborhood_set')

对此:
class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer):
searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True)

class Meta:
model = SearchCity
fields = ('city','searchneighborhood_set')
read_only_fields =('city', 'searchneighborhood_set')

并从这个输出开始:
city: "Chicago"
searchneighborhood_set:
0: 5
1: 4
2: 3
city: "New York"
searchneighborhood_set:
0: 8
1: 7
2: 6

我想要的那个:
city: Chicago
searchneighborhood_set:
0: {pk: 5, neighborhood: 'River North}
....

但是现在出现了一个新问题,主键相关序列化器的意义何在?

关于json - 如何获取主键相关字段嵌套序列化程序 django rest 框架的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49118885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com