Hey all, I'm having some difficulty with my project:

We measure a lot of data per second, so we had to compromise by sending a 
long list to the API, and then having the API create serveral objects:

The data coming in from request.data looks like this:

{
 "datasource": "<serial number>",
 "parameters": ["param_name_1", "param_name_2", "param_name_3" //(... Up to 
100)],
 "data_array": {
 "time": ["time_stamp_1", "time_stamp_2", "time_stamp_3" //(... Up to 100)],
 "values": [param_value_1, param_value_1, param_value_1 //(... Up to 100)]
 }
}



Now, the model looks a little different, where I now have to "parse" the 
above lists into the following model:

class Data(models.Model):
    time = models.DateTimeField(db_index=True)
    sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE)
    parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE)
    parameter_value = models.FloatField()


So, for clarity's sake, using the above example, I have to create 3 
different objects:

Object 1 =
    time = time_stamp_1
    sensor = <serial number>
    parameter = param_name_1
    parameter_value = param_value_1


Object 2 =
    time = time_stamp_2
    sensor = <serial number>
    parameter = param_name_2
    parameter_value = param_value_2


Object 3 =
    time = time_stamp_3
    sensor = <serial number>
    parameter = param_name_3
    parameter_value = param_value_3


Now I thought, easy, I'll create a loop inside the create function!

Just in case: this is my serializers.py:

class DataCreateSerializer(ModelSerializer):
 class Meta:
 model = Data
 fields = [
 'id',
 'time',
 'sensor',
 'parameter',
 'parameter_value'
 ]

On my views.py I thought I could just override the create like so:

class DataCreateAPIView(CreateAPIView):
    queryset = Data.objects.all()
    queryset = queryset.prefetch_related('sensor', 'parameter')
    serializer_class = DataCreateSerializer(queryset, many=True)
    permission_classes = [IsSensor]

    def create(self, request, *args, **kwargs):
        try:
            sensor = Sensor.objects.get(serial_number=request.data[
"datasource"])
            # request.data["datasource"] = sensor.id
        except:
            print("Sensor serial number " + str(request.data["datasource"]) 
+ " not registered.")


        dataDict = dict(request.data) # Turn data into dict, to get inner 
lists
        parameters = dataDict["parameters"] # Break down my dict into lists
        time_stamps = dataDict["data_array"]["time"] # Break down my dict 
into lists
        values = dataDict["data_array"]["values"] # Break down my dict into 
lists


        for param, time, value in zip(parameters, time_stamps, values): # 
Zip lists into one list for each index value. They will always correspond.
            parameter = Parameter.objects.get_or_create(parameter_name=param
, parameter_position="None")[0]
            request.data.update({
                "sensor": sensor.id,
                "parameter": parameter.id,
                "parameter_value": value,
                "time": time
                })
        
            serializer = DataCreateSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            return Response(serializer.errors)


The first "try..except" is just validation to check whether that sensor 
exists in our DB.

Then I thought, get the request.data, break that down into lists, and then 
zip() those lists into the objects that I need, and do the serializer.save 
inside the loop, so it happens as many times as there are elements in the 
list.

There will always be the same amount of items in each of the lists, if 
there are 100 parameters, there will be 100 time stamps, and there will be 
100 parameter values. So looping over the lists seems simple enough.

The problem seems to be that it stops at the first one. The line "return 
Response(serializer.data)" seems to be exiting the for loop entirely, so it 
doesn't go back and create another object with the next zipped item on the 
list.

At this point I've been googling for a few hours and trying different 
things, but nothing seems to work so far.

Any pointers? I can provide other models, views, or URLs if needed.

For clarification, the above code works, ONLY on the first object created, 
it doesn't go back in the loop and creates the second or third.

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to