汤姆克里斯蒂帮助我了解了一些使用REST框架的正确方向,但我现在遇到了另一个问题:
注意:这是使用viewsets.ModelViewSet
在我的原始代码中,我可以通过在模型实例xyz(包含“20x40x50”等坐标数据)上使用带分割()的zip()来返回坐标JSON数据。 我调用了自己的toJSON()函数来使JSON-ready输出我需要的一切。 它出现了类似的东西:
[
{
"id" : "4"
"x" : "500",
"Y" : "80",
"z" : "150"
"color" : "yellow"
},
...
]
使用REST Framework序列化程序的问题是我只知道如何执行serializers.Field(source“xyz”)的事情。我不知道如何将“x”“y”“z”作为单独的字段返回,而不是将“xyz”作为一个大字段返回。
这是我的代码:
serializers.py:
---------------
class NoteSerializer(serializers.ModelSerializer):
owner = serializers.Field(source='owner.username')
firstname = serializers.Field(source='owner.first_name')
lastname = serializers.Field(source='owner.last_name')
x = ???
y = ???
z = ???
class Meta:
model = Note
fields = ('id','owner','firstname','lastname','text','color', 'x', 'y, 'z', 'time')
以下是观点:
views.py:
---------
def list(self, request, format=None):
if request.method == 'GET':
queryset = Note.objects.filter(owner=request.user)
serializer = NoteSerializer(queryset, many=True)
if 'text' in request.GET:
if self.is_numeric(request.GET['id']) and self.is_numeric(request.GET['x']) and self.is_numeric(request.GET['y']) and self.is_numeric(request.GET['z']):
serializer = NoteSerializer(data=request.QUERY_PARAMS)
intx = int(float(request.GET['x']))
inty = int(float(request.GET['y']))
intz = int(float(request.GET['z']))
serializer.object.xyz = str(intx) +'x'+ str(inty) +'x'+ str(intz)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
def create(self, request, format=None):
serializer = NoteSerializer(data=request.DATA)
if serializer.is_valid():
serializer.object.owner = request.user
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
这是我的模特:
from django.db import models
import datetime
import json
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.core import serializers
from django.contrib.auth.models import User
class Note(models.Model):
owner = models.ForeignKey('auth.User', null=True)
text = models.CharField(max_length=500)
color = models.CharField(max_length=20)
xyz = models.CharField(max_length=20)
time = models.DateTimeField((u"Note Creation Date and Time"), auto_now_add=True, blank=True)
def __unicode__(self):
return unicode(self.owner)
非常感谢您的帮助!我是Python / Django / REST的新手。这看起来非常有趣,但几天来让我感到沮丧。
更新:
我似乎无法使用serializer.object.xyz通过views.py访问xyz。它说同样的错误“Nonetype没有属性xyz”
serializer = NoteSerializer(data=request.QUERY_PARAMS)
intx = int(float(request.GET['x']))
inty = int(float(request.GET['y']))
intz = int(float(request.GET['z']))
serializer.object.xyz = str(intx) +'x'+ str(inty) +'x'+ str(intz)
serializer.save()
答案 0 :(得分:2)
您可以尝试使用get_serializer_context将x,y,z发送到序列化程序,例如......
from core import models
from rest_framework import generics
from rest_framework import serializers
class BloopModelSerializer(serializers.ModelSerializer):
x_coord = serializers.SerializerMethodField('get_x')
def get_x(self, instance):
return self.context['x']
class Meta:
model = models.Bloop
class BloopAPIView(generics.ListCreateAPIView):
serializer_class = BloopModelSerializer
queryset = models.Bloop.objects.all()
def get_serializer_context(self):
context = super(BloopAPIView, self).get_serializer_context()
# you have access to self.request here
context.update({
'x': 1111,
'y': 2222
})
return context
这样您就不必再覆盖列表并创建函数了。
另外,您还可以尝试将您的坐标放入自己的序列化程序中,并将它们分组到序列化程序中。 rest_framework可以嵌套序列化器,因此你可以添加一个CoordinatesSerializer
类,你的模型序列化器看起来像这样
class CoordinateSerializer(serializers.Serializer):
x = models.Field()
y = models.Field()
# ...
class BloopModelSerializer(serializers.ModelSerializer):
coordinates = CoordinateSerializer('get_coords')
def get_coords(self, instance):
return self.context['coords']
class Meta:
model = models.Bloop
答案 1 :(得分:2)
我的方法:
COORD = dict(x=0, y=1, z=2)
class CoordinateField(serializers.Field):
def field_to_native(self, obj, field_name):
# retrieve and split coordinates
coor = obj.content.split('x')
# get coordinate value depending on coordinate key (x,y,z)
return int(coor[COORD[field_name]])
def field_from_native(self, data, files, field_name, into):
into['xyz'] = u'{x}x{y}x{z}'.format(**data)
super(CoordinateField, self).field_from_native(data, files, field_name, into)
class BloopModelSerializer(serializers.ModelSerializer):
x = CoordinateField()
y = CoordinateField()
z = CoordinateField()
class Meta:
model = Bloop
这就是我得到的结果:
{
"x": 10,
"y": 20,
"z": 30,
"content": "10x20x30"
},
修改强>
views.py
class BloopList(generics.ListCreateAPIView):
queryset = Bloop.objects.all()
serializer_class = BloopModelSerializer
bloop_list = Bloop.as_view()
urls.py
url(r'^api/bloops/$', 'myapp.views.bloop_list', name='bloop-list'),
<强> SUGGESTION 强>
您不应该使用list GET方法来更改/添加对象,DRF具有内置类,使其非常简单,并使您遵循正确的REST标准。
例如,你的list方法使用GET参数获取请求数据,这是一个坏主意,每当你更新或添加新对象时,你应该使用POST或PUT在请求体内提供数据。 DRF假定,这是提供数据的方式并处理所有事情。