how to get all values of primary key related field nested serializer django rest framework

我与影子孤独终老i 提交于 2019-12-24 01:14:25

问题


I have the following models:

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)

and then the following nested serializer:

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')

paired with the view:

class CityNeighborhoodView(ListAPIView):
    queryset = SearchCity.objects.all()
    serializer_class = CityNeighborhoodReadOnlySerializer

when I make the api call I get this:

city: "Chicago"
    searchneighborhood_set: 
      0: 5 
      1: 4
      2: 3
city: "New York"
    searchneighborhood_set:
      0: 8
      1: 7
      2: 6

Im just getting the primary keys of the objects related. Which is good I need that, but I also want the neighborhood name how do I get that?

edit:

This question may shead some light. They are not using the primary key related serializer though, so my question would be (if this works of course, is what is the point of the primarykey related serializer then?

Django Rest Framework nested serializer not showing related data


回答1:


The answer was to not use the primarykeyrelatedserializer but rather the serializer used to serialize Searchneighborhood objects.

I changed this:

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')

to this:

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')

and went from this output:

city: "Chicago"
    searchneighborhood_set: 
      0: 5 
      1: 4
      2: 3
city: "New York"
    searchneighborhood_set:
      0: 8
      1: 7
      2: 6

to the one I wanted:

city: Chicago
    searchneighborhood_set:
         0: {pk: 5, neighborhood: 'River North}
    ....

but now a new question arises, what is the point of a primary key realated serializer?



来源:https://stackoverflow.com/questions/49118885/how-to-get-all-values-of-primary-key-related-field-nested-serializer-django-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!