so I know my question is horribly written but I'm not sure the best way to phrase this. Let me explain.
I'm trying to get my serializer class to process multiple value types for a specific field. For example, I need to Post the JSON values of items called "Temp (C)", "Humidity(%)", etc all under a specific field called "value" in my serializer class. I also of course have a model in models.py called "value".
This is what I have so far:
models.py
class DataValueTable(models.Model):
timestamp = models.FloatField()
sensorName = models.TextField(null=True)
value = models.FloatField()
views.py
class DataValueTableList(APIView):
parser_classes = [JSONParser]
authentication_classes = []
permission_classes = []
def post(self, request, format=None):
serializer = DataValueTableSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.py
class DataValueTableSerializer(serializers.ModelSerializer):
class Meta:
model = DataValueTable
fields = ['id', 'System Time', 'Node ID', 'Temp (C)', 'Humidity(%)', 'Pyra (WPM)',]
extra_kwargs = {
"Node ID": {"source": "sensorName"},
"System Time": {"source": "timestamp"},
"Temp (C)": {"source": "value"},
"Humidity(%)": {"source": "value"},
"Pyra (WPM)": {"source": "value"},
}
def create(self, validated_data):
return DataValueTable.objects.create(**validated_data)
For the serializer.py: The values im posting as JSON are different than the model names in models.py so I'm using "extra_kwargs" to map the JSON names to the models.
Here's what I'm trying to Post:
{
"Node ID": "2",
"Temp (C)": "22.6",
"Humidity(%)": "29.67",
"Pyra (WPM)": "118.9",
"System Time": "1592287220"
}
Here's the response:
{
"id": 126,
"System Time": 1592287220.0,
"Node ID": "2",
"Temp (C)": 2.69,
"Humidity(%)": 2.69,
"Pyra (WPM)": 2.69,
}
I was able to get all of those JSON items to Post, but the values are the same for each one which isn't good. I know what's wrong, the "validated_data" in the "def create" method only keeps track of the data up until the first instance of "value", then it stops. In this case it goes through my "fields" list in my DataValueTableSerializer class and stops at "Temp (C)" because that's the first instance of "value".
So here's my question: Is there a way to access this JSON data being Posted before it gets truncated in the "def create" method in the DataValueTableSerializer class? I'm hoping if I can access the data I could maybe manually map the values I need similar to how I did in "extra_kwargs". Or if someone knows of an even better method than what I'm trying to do that would be amazing!