user1462141
user1462141

Reputation: 252

Django filter update specific field based on ajax return

I have a ajax post that returns the following data:

{u'related_id': u'9', u'db_name': u'my_field', u'name': u'jsaving_draft', u'value': u'hypothesis sadfasdfadfws asdfasdf'}

In my view I have:

if request.is_ajax():                                                                                                                   
     if "jsaving_draft" in request.body:                                                                                                 
         results = json.loads(request.body)                                                                                              
         print results                                                                                                                   
         save_id = results['related_id']                                                                                                 
         save_db = results['db_name']                                                                                                    
         save_value = results['value']
         temp = Dbtable.objects.filter(id=save_id).update(save_db=save_value)

How can I specify the specific table element to update based on save_db without hardcoding the database row name. I have a table in my database named.

I tried doing something like like:

Dbtable.objects.filter(id=save_id).update("%s"=save_value) % save_db    

but that failed spectacularly. Does anyone have an idea of how I can make this work?

Upvotes: 2

Views: 734

Answers (1)

alecxe
alecxe

Reputation: 473873

You can use keyword argument unpacking:

Dbtable.objects.filter(id=save_id).update(**{save_db: save_value}) 

Example:

>>> def test(a,b):
...     return a + b
... 
>>> test(**{'a': 1, 'b': 2})
3

Upvotes: 2

Related Questions