[Fixed]-Dealing with foreign key in create view in django rest framework

1👍

One way is to alias the field into the nested object and make the aliased nested object read-only:

class BarSerializer(serializers.ModelSerializer):
    foo_obj = FooSerializer(required=False,read_only=True)
    class Meta:
        model = Bar
        fields = ('pk', 'foo', 'foo_obj', 'name')

If foo is present, then it is placed in Bar‘s foo_obj field. On the client side, you’ll have to keep foo and foo_obj in sync’, which really stinks.

0👍

  1. How can it be done: one way to achieve this is to play around with 2 serializers, which you will select based on the request type:
    class BarSerializer(serializers.ModelSerializer):
        class Meta:
            model = Bar
            fields = ('pk', 'foo', 'name')

    class BarNestedSerializer(BarSerializer):
        class Meta(BarSerializer.Meta):
            depth = 2


    class BarView(generics.ListCreateAPIView):
        queryset = Bar.objects.all()

        def get_serializer_class(self):
            return BarNestedSerializer if self.action == 'list' else BarSerializer
  1. How it should be done: have a separate route for Foo objects, which you will cache on the front-end and display their lookup value based on the ID. At the end of the day, it really depends on your usecase, but normally one should be able to avoid nesting, only if strictly necessary.
👤Roba

Leave a comment