我有一个目标,即在嵌套序列化程序中的请求响应中将城市及其邻居链接在一起。社区有一个Foriegn关键城市。
为了清楚起见,这里是我最初使用的模型和序列化器。
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')
但是只返回了邻近的主键,城市不是完整的城市对象。
这:
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}
....
我得到了上述请求,不是通过使用primarykeyrelatedserializer,而是使用用于序列化邻居对象的序列化程序,如下所示:
class SearchNeighborhoodSerializer(serializers.ModelSerializer):
class Meta:
model = SearchNeighborhood
fields = ('pk','neighborhood')
所以现在用我的邻居替换primarykeyrealatedserializer并且正确的嵌套serailzer是这样的:
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')
所以这就引出了一个问题,主键关系序列化器的实际用例是什么?
这也是我创建的一个问题然后回答了自己,经过实验,我提出了这个问题。
how to get all values of primary key related field nested serializer django rest framework
答案 0 :(得分:1)
有些消费者只想要/需要对象的主键,实际上就没那么了。它只是设计应用程序的另一种方式。