I'm producing an API that uses DRF to receive Arduino's data and send it to Android. First of all, we succeeded in creating an API that shows the values stored in DB. However, there is a problem in producing an API that sends Arduino's data to DB. Data is normally input, but this data is not stored. Can you tell me the problem of my code? here is my codes
views.py
from .models import arduino
from .serializers import arduinoSerializers
from rest_framework.viewsets import ViewSet, ModelViewSet
from rest_framework.response import Response
class arduinoToAndroidViewSet (ViewSet) :
def dataSend (self, request) :
user = self.request.user
queryset = arduino.objects.filter(name=user)
serializer = arduinoSerializers(queryset, many=True)
return Response(serializer.data)
class arduinoToDatabaseViewSet (ModelViewSet) :
serializer_class = arduinoSerializers
def get_queryset(self) :
user = self.request.user
return arduino.objects.filter(name=user)
def dataReceive(self, request) :
queryset = get_queryset()
serializer = arduinoSerializers(queryset, many=True)
serializer.save()
return Response(serializer.data)
serializers.py
from rest_framework import serializers
from .models import arduino
class arduinoSerializers (serializers.ModelSerializer) :
name = serializers.CharField(source='name.username', read_only=True)
class Meta :
model = arduino
fields = ('name', 'temp', 'humi')
models.py
from django.db import models
from django.contrib.auth.models import User
class arduino (models.Model) :
name = models.ForeignKey(User, related_name='Username', on_delete=models.CASCADE, null=True)
temp = models.FloatField()
humi = models.FloatField()
def __str__ (self) :
return self.name.username
If you are referring to the problem that your dataReceive(self, request)
method is not saving data despite of having a valid queryset
(could not understand why you are querying and saving the save object again), is because you have to always call is_valid()
before attempting to save. so it should be
def dataReceive(self, request) :
queryset = get_queryset()
serializer = arduinoSerializers(queryset, many=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.