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

5👍

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

0👍

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

Leave a comment