简体   繁体   中英

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

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM