Django rest framework - Pass id of newly created object back with response after POST

What I want to do is pass the id of a job back to the client, after it has been posted to the server and saved.

In other words. I am getting this response:

Object {address: "My address", description: "This is a test job", duration: "2.0", price: 300, title: "Test"}

This is the response I want:

Object {id: "Some id", address: "My address", description: "This is a test job", duration: "2.0", price: 300, title: "Test"}

This is what I have:

My view:

class JobViewSet(viewsets.ModelViewSet):

    queryset = Job.objects.all()
    serializer_class = JobSerializer

    permission_classes = (permissions.IsAuthenticated,IsOwnerOrReadOnly,)
    filter_fields = ('is_published')

    def perform_create(self, serializer):
        geolocator = GoogleV3()

        location = geolocator.geocode(serializer.data['address'])

        if location:
            geom = {'type': 'Point', 'coordinates': [location.longitude, location.latitude]}
        else:
            geom = None

        serializer.save(creator = self.request.user, geom=geom)

My serializer:

class JobSerializer(serializers.ModelSerializer):

    creator = serializers.ReadOnlyField(source='creator.id')

    num_applicants = serializers.ReadOnlyField()
    popup_content = serializers.ReadOnlyField()
    time_since_created = serializers.ReadOnlyField()

    class Meta:
        model = Job
        fields = (
            'id',
            'title',
            'description',
            'creator',
            ...
        )

I know that if I change the last line in the view to

job = serializer.save(creator = self.request.user, geom=geom)

I can simply get the id by calling job.id, however I can not find a way to add it to the response. Or if the response is already sent by this stage.

I guess that the answer would be something like overriding the .save() or .create() method of the serializer.

Upvotes: 3

Views: 3809

Answers (2)

Amen
Amen

Reputation: 1633

Although this is an old question as I came across the same problem and found the answer I though I'd share it. You should use this line in your serializer:

id = serializers.ReadOnlyField()

Upvotes: 2

pingul
pingul

Reputation: 3473

If you use the generic views a "post" function is provided to, and it looks by default like

def post(self, request, *args, **kwargs):
    return self.create(request, *args, **kwargs) # A Response object with the data you saved

You could instead return pretty much anything you want:

def post(self, request, *args, **kwargs):
    self.create(request, *args, **kwargs)
    job = # Fetch the object you just created and serialize it
    return Response(job)

Upvotes: 1

Related Questions