如何读取数据,应用函数并使用Django REST Framework返回结果?

时间:2016-08-23 01:46:29

标签: python json django django-rest-framework

考虑一个简单的任务来计算“y = ax + b”,其中“a”和“b”由模型给出,“x”由用户通过API请求给出,如http:// someurl .com / api / 15,其中x = 15。

通常,API会以JSON格式返回“a”和“b”。但是,相反,我想在服务器上解决这个等式,只返回“y”。但是,我无法弄清楚如何从URL获取“x”以及将最后一个函数放在哪里以将“y”返回给JSON。有什么想法吗?

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

到目前为止我的愚蠢功能:

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

2 个答案:

答案 0 :(得分:2)

使用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

答案 1 :(得分:0)

URL dispatcher将捕获该值并将其传递给视图。这样的事情可能有用:

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