1

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

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.