Erick Damasceno
Erick Damasceno

Reputation: 85

How to read data, apply a function and return the result with Django REST Framework?

Consider a simple task to calculate "y = ax + b", where "a" and "b" are given by the model and "x" is given by the user through an API request, like http://someurl.com/api/15, where x=15.

Usually, the API would return "a" and "b" in a JSON format. But, instead, I want to solve this equation on the server and only return "y". However, I can't figure it out how to get "x" from the URL and where to place the last function to return "y" to the JSON. Any thoughts?

models.py:

from django.db import models

class SimpleEquation(models.Model):
    a = models.IntegerField()
    b = models.IntegerField()

serializers.py:

from rest_framework import serializers
from .models import SimpleEquation

class SimpleEquationSerializer(serializers.ModelSerializer):
    class Meta:
        model = SimpleEquation
        fields = ('a','b') # Should return 'y' instead

views.py:

from rest_framework import generics
from .serializers import SimpleEquationSerializer

class Results(generics.ListAPIView):
    queryset = SimpleEquation.objects.all()[0]
    serializer_class = SimpleEquationSerializer

My dumb function so far:

def the_function(request):
    x = SOME_REQUEST_GET_METHOD
    pars = SimpleEquation.objects.all()[0]
    a = pars.a
    b = pars.b
    y = a*x + b
    return y

Upvotes: 3

Views: 1747

Answers (2)

Aswin Kumar K P
Aswin Kumar K P

Reputation: 1102

Use Serializer Method Field

from rest_framework import serializers
from .models import SimpleEquation

class SimpleEquationSerializer(serializers.ModelSerializer):

    y = serializers.SerializerMethodField('get_y')

    class Meta:
        model = SimpleEquation
        fields = ('y')

    def get_y(self, obj):
        x =  self.context['request'].x
        y = obj.a*x + obj.b  # obj comes from the queryset from view
        return y

Upvotes: 5

Alexander
Alexander

Reputation: 109546

The URL dispatcher would capture the value and pass it to the view. Something like this may work:

URLconf

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^regression/[+-]?\d+.\d+?/$', views.regression),
]

views.py

def regression(request, x)
    x = float(x)
    pars = SimpleEquation.objects.all()[0]
    a = pars.a
    b = pars.b
    y = a*x + b
    return y

Upvotes: 0

Related Questions