Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding field in Django Rest Framework generics.ListAPIView

I have a view that can be called with a longitude and latitude parameters.

When those parameters are set, I want the response to add the distance fields in the serialization.

Here is how I do that:

def get_queryset(self):
    latitude = self.request.QUERY_PARAMS.get('latitude', None)
    longitude = self.request.QUERY_PARAMS.get('longitude', None)
    if latitude and longitude:
        center = fromstr('POINT(%s %s)'%(latitude,longitude))
        queryset = queryset.distance(center).order_by('distance')
        self.serializer_class.distance = serializers.CharField(source='distance')
        self.serializer_class.Meta.fields += ('distance',)
    return queryset.all()

I think I could have done if differently, with two separate serializer_class.

I am wondering if it would have been better, what do you think?

like image 643
Benjamin Toueg Avatar asked Aug 23 '26 02:08

Benjamin Toueg


1 Answers

I guess distance is None where longitude and latitude aren't given?

I'd be inclined to define the distance field on the serializer itself, rather than adding it dynamically on the view.

For the case where distance is None — if I didn't want it in the response — I would override to_native on the serializer to remove it. E.g:

def to_native(self, obj):
    ret = super(MySerializer, self).to_native(obj)
    if ret['distance'] is None:         
        del ret['distance']
    return ret

The end result is the same but this approach is more cohesive. I hope that helps.

like image 126
Carlton Gibson Avatar answered Aug 25 '26 15:08

Carlton Gibson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!