Dears,
I have a problem with adding some new variables to the serializer data that comes from the MQTT application.
Our Models.py:
class Log (models.Model):
LID = models.ForeignKey(‘New_device’, on_delete=models.CASCADE)
DevID = models.IntegerField(null=False, default=0)
TIME = models.IntegerField(null=False)
CODE = models.IntegerField(default=0)
COMPRESSOR_STATUS = models.IntegerField(default=0)
DEFORST_STATUS = models.IntegerField(default=0)
FAN_STATUS = models.IntegerField(default=0)
ERROR_STATUS = models.IntegerField(default=0)
VOLTAGE = models.IntegerField(default=0)
CURRENT = models.IntegerField(default=0)
SP = models.IntegerField(default=0)
PB1 = models.IntegerField(default=0)
PB2 = models.IntegerField(default=0)
PB3 = models.IntegerField(default=0)
PB4 = models.IntegerField(default=0)
ECO = models.IntegerField(default=0)
IO2 = models.IntegerField(default=0)
def str(self):
return f"{self.id, self.CODE, self.TIME, self.PB1, self.PB2, self.PB3, self.PB4}"
class LogForm(forms.ModelForm):
class Meta:
model = Log
fields = (“LID”, “COMPRESSOR_STATUS”, “DEFORST_STATUS”, “FAN_STATUS”, “ERROR_STATUS”, “VOLTAGE”, “CURRENT”,
“SP”, “PB1”, “PB2”, “PB3”, “PB4”, “ECO”, “IO2”)
Our serializer.py:
from rest_framework import serializers
from .models import Log
class LogSerializer(serializers.ModelSerializer):
class Meta:
model = Log
fields = [“TIME”, “CODE”, “COMPRESSOR_STATUS”, “DEFORST_STATUS”, “FAN_STATUS”, “ERROR_STATUS”, “VOLTAGE”, “CURRENT”, “SP”, “PB1”, “PB2”, “PB3”, “PB4”, “ECO”, “IO2”]
and our views.py:
class LogItemViews(APIView):
def post(self, request):
serializer = LogSerializer(data=request.data)
devid = request.GET[‘DevID’]
#serializer.save(COMMIT=False)
Log.DevID = devid
id = New_Device.objects.filter(serial_number=devid).values_list(‘id’, flat=True)[0]
Log.LID_id = id
if serializer.is_valid():
serializer.save()
get_code = request.data[‘CODE’]
if get_code > “1600”:
print (get_code, “A message has sent”)
return (send_sms(‘hello’, ‘phone number’))
return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
else:
return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, id=None):
if id:
item = Log.objects.get(id=id)
serializer = LogSerializer(item)
return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
items = Log.objects.all()
serializer = LogSerializer(items, many=True)
return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
#In our scenario, we get JSON packages from the MQTT broker. We can save them in our DB without any problems but when we want to add new variables like LID(it is a foreign key to another DB Model that we want to fill from the backend) and DevID( which received it through the payload of MQTT Code) we got errors.
So I want to know if anybody can help me for finding a valuable solution for it.
Frankly, I have some idea but nothing of them were facilitated.