型号.py
class Server(models.Model):
label = models.TextField(max_length=200,null=True) #compare this
upload1 = models.FileField(null=True, blank=True)
Image1 = models.TextField(upload1, null=True)
class Android(models.Model):
label=models.TextField(max_length=200,null=True) #with this
imagestring=models.TextField(null=True,blank=True)
returnlabel=models.TextField(null=True,blank=True)
因此,在我的序列化程序类中,我在(defget_returnlabel(中比较Android模型和服务器模型的标签,我想将这个标签返回到我的Android应用程序。关于如何做到这一点的任何建议。在我的android应用程序上,我使用异步http。
序列化程序.py
class FoodSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model=Server
fields=('url','label','Image1','upload1')
class AndroidSerializers(serializers.ModelSerializer):
class Meta:
model = Android
fields = ('label', 'imagestring', 'returnlabel') (<--returnlabel back to android app)
#Compare label from Server and Android
def get_return_label(self, obj):
queryset = Server.objects.filter( labelServer=obj.label)
queryset_serializer = FoodSerializers( queryset, many=True, read_only=True)
return queryset_serializer.data
视图.py
class FoodViewSet(viewsets.ModelViewSet):
queryset = Server.objects.all()
serializer_class =FoodSerializers
class Androids(viewsets.ModelViewSet):
queryset =Android.objects.all()
serializer_class = AndroidSerializers
假设我正确理解了你的问题,并且你基本上是在问如何将get_return_label()
的输出返回到你的Android客户端,那么你应该能够在你的视图集中为此创建一个额外的操作。您需要首先将get_return_label()
重新定位到视图集中。
例如:
from rest_framework.response import Response
class FoodViewSet(viewsets.ModelViewSet):
queryset = Server.objects.all()
serializer_class = FoodSerializers
@action(detail=False, methods=['post'])
def get_return_label(self, request):
obj = request.data # The RecognizingFood object posted by the client
queryset = Server.objects.filter(label=obj['label'])
queryset_serializer = FoodSerializers(queryset, many=True, read_only=True)
return Response(queryset_serializer.data)
要访问它,您需要使用附加了/get_return_label/
的FoodViewSet
的现有URL
另一种选择是创建一个专用的视图端点:
from rest_framework import views
class GetReturnLabelView(views.APIView):
def post(self, request):
obj = request.data # The RecognizingFood object posted by the client
queryset = Server.objects.filter(label=obj['label'])
queryset_serializer = FoodSerializers(queryset, many=True, read_only=True)
return Response(queryset_serializer.data)
def get(self, request):
queryset = Server.objects.filter(label=request.data['label'])
queryset_serializer = FoodSerializers(queryset, many=True, read_only=True)
return Response(queryset_serializer.data)
并将其映射到您的urls.py
:中
path(r'get_return_label', views.GetReturnLabelView.as_view())