I am working with django models. I want to pass a model field as a variable. Given my function:
from django.models import models
def updatetable(value, fieldtitle, tablename, uid, refname):
workingobj = tablename.objects.get(refname=uid)
currentvalue = getattr(workingobj, fieldtitle)
setattr(workingobj, fieldtitle, currentvalue + value)
workingobj.save()
return
I have tried:
updatetable(len(sr), 'posts_added', managementmetrics, startdtg, refname=update_dtg_start)
updatetable(len(sr), 'posts_added', managementmetrics, startdtg, refname='update_dtg_start')
and even
updatetable(len(sr), 'posts_added', managementmetrics, startdtg, {refname:update_dtg_start})
I get the error: Cannot resolve keyword 'refname' into field. Choices are: length_of_update, update_dtg_finish, update_dtg_start
I've tried switching out refname for **kwargs but still can't seem to get it to take the field value.
The problem is not in how you call this function: the function itself does not do what you want.
You need to change how you call get
. Rather than passing in refname directly, you need to use the dict there :
workingobj = tablename.objects.get(**{refname: uid})
Now you simply call the function in the normal way:
updatetable(len(sr), 'posts_added', managementmetrics, startdtg, 'update_dtg_start')
(You should also consider renaming the tablename
parameter: you are not passing a table name, which implies a string, but a model class object.)
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.