r.bhardwaj
r.bhardwaj

Reputation: 1613

Use additional request param to generate a model field in DRF 3

I am new to Djnago Rest Framework 3 and not able to understand how to achieve this:
I have following model:

class Interface(models.Model):  
    name = models.CharField(max_length=25)
    current_location = models.CharField(max_length=25, blank=True)

And in request param, I am expecting latitude, longitude field which will generate the geohash from latitude, longitude and store in current_location.

I tried using following serializer and ViewSet, but it is giving error

'Interface' object has no attribute 'latitude'.

class InterfaceSerializer(serializers.ModelSerializer):
    latitude = serializers.FloatField()
    longitude = serializers.FloatField()
    class Meta:
        model = Interface
        fields = ('id', 'name', 'latitude', 'longitude',)
        read_only_fields = ('id',)

class InterfaceViewSet(viewsets.ModelViewSet):
"""                                                                                                                                              
API endpoint that allows interface to be viewed or edited.                                                                                       
"""
    queryset = Interface.objects.all()
    serializer_class = InterfaceSerializer

Even using the serializers.Serializer instead of serializers.ModelSerializer gives same error.
What is wrong here ?
How to structure the serializer for given model and requirement ?

Upvotes: 0

Views: 109

Answers (1)

Ivan Semochkin
Ivan Semochkin

Reputation: 8907

How do you think serializer will know about purpose of latitute and longitute fields?
You should override create method and set you current_location manually

class InterfaceSerializer(serializers.ModelSerializer):
    latitude = serializers.FloatField()
    longitude = serializers.FloatField()

    class Meta:
        model = Interface
        fields = ('id', 'name', 'latitude', 'longitude',)

    def create(self, validated_data):
        latitute = validated_data.get('latitude')
        longitude = validated_data.get('longitude')
        name = validated_data.get('name')
        # suppose you want to store it charfield comma separated
        current_location = str(latitute) + ',' + str(longtitute)
        return Interface.objects.create(
                         current_location=current_location,
                         name=name
                         )

There is also useful package django-geoposition it provides field and widget for geoposition.

Upvotes: 1

Related Questions