Reputation: 1932
How do you set the results of a Django query to equal a new set of variables? for example, when I run this query on my Django shell:
getDefaults = defaultParams.objects.filter(isDefault = True, device = 41)
then run:
for val in getDefaults.values():
print(val)
It returns:
{'id': 2, 'device_id': 41, 'customerTag': 'ABCD001', 'isDefault': True}
I would like to use the values in this dictionary to save a new record into my database, but can't seem to extract the values from the dictionary? I thought it would be something like:
device_id = getDefaults.device_id
NewCustomerTag = getDefaults.customerTag
Upvotes: 0
Views: 881
Reputation: 696
you can not do getDefaults.device_id since defaultParams.objects.filter return a list of matched objects.
If you are sure you get a single match do as follows.
device_id = getDefaults[0].device_id
NewCustomerTag = getDefaults[0].customerTag
or
you can iterate through the list and use the dict data.
for val in getDefaults:
device_id = val.device_id
NewCustomerTag = val.customerTag
If you want to save the retrieved object info as new object I would suggest the following approach.
getDefaults = defaultParams.objects.filter(isDefault = True, device = 41)
getDefaults[0].pk = None
getDefaults[0].save()
Upvotes: 1
Reputation: 599550
values()
explicitly returns a list of dictionaries, so you would need to use dictionary syntax: val['device_id']
.
But in your case there is no reason to do that. Skip the values
call altogether, and you will get an instance of defaultParams on which you can use normal attribute lookups:
for val in getDefaults:
print(val.device_id)
Upvotes: 1