4

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 Answer 1

7

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.