Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework : How to add a custom field to the response of the GET request?

I'm new to DRF and have just started building an API.

I've a model called Shop. And I've two user different user types : Customer and Supplier.

  1. I want to add a custom field distance to the response of the GET request /shops/id/, which represents the distance between the Customer that is submitted the request and the corresponding shop.
  2. I think I cannot use SerializerMethodField since the value of the method is not only depend on the object itself.
  3. I do not want to add this custom field for all GET requests, instead, I need to add it, when the user that is submitted the request is a Customer.

Considering constraints above, how should I add the custom field to the response of the request? What's the best way to do this ?

like image 332
hnroot Avatar asked Jun 21 '16 11:06

hnroot


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is request POST get in Django?

Django get POST data as dictWhen you submit data or parameters through a POST request to a Django application, these parameters are stored in the form of a dictionary-like object of the class QueryDict. This object is a dictionary-like object i.e. you can use almost all the functions of a dictionary object.

What is Queryset in Django REST framework?

queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True .


1 Answers

You can define a distance SerializerMethodField, and there access the current user location using serializer's context. Then compute distance using current user location and shop's location.

class ShopSerializer(serializers.ModelSerializer):

    distance = serializers.SerializerMethodField()

    class Meta:
        model = Shop
        fields = (.., 'distance')

    def get_distance(self, obj):
        current_user = self.context['request'].user # access current user    
        user_location = current_user.location

        distance = <compute distance using obj.location and user_location>
        return distance
like image 93
Rahul Gupta Avatar answered Sep 28 '22 15:09

Rahul Gupta