简体   繁体   中英

How to manually populate Django model data for insert

I'm trying to store a list of timings for a speed test.

All timings are serialized clientside and sent to the server via ajax.

Model:

class SpeedTest(models.Model):
    t1 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True)
    t2 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True)
    t3 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True)
    ...
    ...
    ...
    t100+ = ...

View:

def save(request):
    results = json.loads(request.POST.get('results'))

    speed_test = SpeedTest.objects.create()

    for result in results:
        key = "t"+str(result['key'])
        speed_test.key = value

    speed_test.save()

Where results has the form:

results[0]['key'] = 1
results[0]['value'] = 0.539
results[1]['key'] = 2
results[1]['value'] = 0.654
results[2]['key'] = 3
results[2]['value'] = 0.426
...
...
...
results[100+]...

I am trying to loop through all the t1 - t100+ values and add them to my model object. Ie a loop to do:

speed_test.t1 = 0.539
speed_test.t2 = 0.654
speed_test.t3 = 0.426
...
etc

These lines are not doing the job.

key = "t"+str(result['key'])
speed_test.key = value

What is the correct way to do this?

this is question is answered within a different context here How to set django model field by name? .

To explain it a bit further and with your code as example:

Construct the Fieldname via key = "t"+str(result['key']) ,

Set the desired value via setattr(speed_test, key, result['value'])

And after the loop, don't forget to call speed_test.save() .

One personal Recomendation:

If you are looking forward to more work correlated with AJAX/JSON you might want to consider Django-REST-Framework for it's Serializer which handle such stuff quite good for simple/flat cases (you current problem would be in such category).

NOTE: In your given example data

results[0]['key'] = 1
results[0]['value'] = 0.539
results[1]['key'] = 2
results[1]['value'] = 0.654
results[2]['key'] = 2
results[2]['value'] = 0.426

does the third result really OVERWRITE the second ?

Hope this helps.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM