Django - select [column] AS - python-3.x

I have the following code:
MyModel.objects.values('foo','flu','fu').filter(part_of=pk)
which gives me the following dictionary:
{'foo': a, 'flu': b, 'fu': c}
This dictionary is serialized into a JSON response like so:
JsonResponse(data, safe=False)
Is there a way I could rename the key of 'flu' into something while preserving the value?
So far I tried:
values[0]['new_flu'] = values[0].pop('flu')
Which I think is the usual Python way of renaming a dictionary key however this seems to have no effect and the JSON returned still contains 'flu' instead of new_flu.
I feel like this could be simply solved by ALIAS eg. SELECT foo, flu AS new_flu, fu from ..... What would be the Django alternative of this command? Or is there some other solution?

One of the options is to annotate query with names you needed:
from django.models import F
MyModel.objects.filter(part_of=pk).annotate(new_flu=F('flu')).values('foo','new_flu','fu')

Related

How does "object" work in the collections.defaultdict example "%(object)s"?

In the Python3 documentation for collections.defaultdict(), the Examples sections gives an unusual use of "%()s" formatting:
def constant_factory(value):
return lambda: value
d = defaultdict(constant_factory('<missing>'))
d.update(name='John', action='ran')
'%(name)s %(action)s to %(object)s' % d
>>> 'John ran to <missing>'
I'm familiar with the "%()s" notation (though bonus points if someone can point me to the documentation for this usage) but my question is, where does "object" come from? I can't figure out how this works because there is no "object" key in the dict:
print(f"{d=}")
>>> d=defaultdict(<function constant_factory.<locals>.<lambda> at 0x7fa088a5ab80>, {'name': 'John', 'action': 'ran'})
The string formatting line told Python to plug the value of d['object'] into the string. The way a defaultdict works is that if you refer to a key that is not there, it will create an entry with that key and the default value from the factory you gave it. So in this case, when the format string referred to d['object'], the defaultdict created an entry with a key of 'object' and a value of '<missing>' and duly plugged the value into the string.
I would guess that the output of the contents of d you showed was run before the format string reference created the 'object':'<missing>' entry.
For bonus points, so-called "Old Style" string formatting operations with % are documented at https://docs.python.org/2/library/stdtypes.html#string-formatting. Different string formatting facilities were introduced in Python 3.

How to create Multi Dimensional Dictionary

how to make a Multidimensional Dictionary with multiple keys and value and how to print its keys and values?
from this format:
main_dictionary= { Mainkey: {keyA: value
keyB: value
keyC: value
}}
I tried to do it but it gives me an error in the manufacturer. here is my code
car_dict[manufacturer] [type]= [( sedan, hatchback, sports)]
Here is my error:
File "E:/Programming Study/testupdate.py", line 19, in campany
car_dict[manufacturer] [type]= [( sedan, hatchback, sports)]
KeyError: 'Nissan'
And my printing code is:
for manufacuted_by, type,sedan,hatchback, sports in cabuyao_dict[bgy]:
print("Manufacturer Name:", manufacuted_by)
print('-' * 120)
print("Car type:", type)
print("Sedan:", sedan)
print("Hatchback:", hatchback)
print("Sports:", sports)
Thank you! I'm new in Python.
I think you have a slight misunderstanding of how a dict works, and how to "call back" the values inside of it.
Let's make two examples for how to create your data-structure:
car_dict = {}
car_dict["Nissan"] = {"types": ["sedan", "hatchback", "sports"]}
print(car_dict) # Output: {'Nissan': {'types': ['sedan', 'hatchback', 'sports']}}
from collections import defaultdict
car_dict2 = defaultdict(dict)
car_dict2["Nissan"]["types"] = ["sedan", "hatchback", "sports"]
print(car_dict2) # Output: defaultdict(<class 'dict'>, {'Nissan': {'types': ['sedan', 'hatchback', 'sports']}})
In both examples above, I first create a dictionary, and then on the row after I add the values I want it to contain. In the first example, I give car_dict the key "Nissan" and set it's values to a new dictionary containing some values.
In the second example I use defaultdict(dict) which basically has the logic of "if i am not given a value for key then use the factory (dict) to create a value for it.
Can you see the difference of how to initiate the values inside of both of the different methods?
When you called car_dict[manufacturer][type] in your code, you hadn't yet initiated car_dict["Nissan"] = value, so when you tried to retrieve it, car_dict returned a KeyError.
As for printing out the values, you can do something like this:
for key in car_dict:
manufacturer = key
car_types = car_dict[key]["types"]
print(f"The manufacturer '{manufacturer}' has the following types:")
for t in car_types:
print(t)
Output:
The manufacturer 'Nissan' has the following types:
sedan
hatchback
sports
When you loop through a dict, you are looping through only the keys that are contained in it by default. That means that we have to retrieve the values of key inside of the loop itself to be able to print them correctly.
Also as a side note: You should try to avoid using Built-in's names such as type as variable names, because you then overwrite that functions namespace, and you can have some problems in the future when you have to do comparisons of types of variables.

postgres IN clause through python psycopg [duplicate]

What is the correct method to have the list (countryList) be available via %s in the SQL statement?
# using psycopg2
countryList=['UK','France']
sql='SELECT * from countries WHERE country IN (%s)'
data=[countryList]
cur.execute(sql,data)
As it is now, it errors out after trying to run "WHERE country in (ARRAY[...])". Is there a way to do this other than through string manipulation?
Thanks
For the IN operator, you want a tuple instead of list, and remove parentheses from the SQL string.
# using psycopg2
data=('UK','France')
sql='SELECT * from countries WHERE country IN %s'
cur.execute(sql,(data,))
During debugging you can check that the SQL is built correctly with
cur.mogrify(sql, (data,))
To expland on the answer a little and to address named parameters, and converting lists to tuples:
countryList = ['UK', 'France']
sql = 'SELECT * from countries WHERE country IN %(countryList)s'
cur.execute(sql, { # You can pass a dict for named parameters rather than a tuple. Makes debugging hella easier.
'countryList': tuple(countryList), # Converts the list to a tuple.
})
You could use a python list directly as below. It acts like the IN operator in SQL and also handles a blank list without throwing any error.
data=['UK','France']
sql='SELECT * from countries WHERE country = ANY (%s)'
cur.execute(sql,(data,))
source:
http://initd.org/psycopg/docs/usage.html#lists-adaptation
Since the psycopg3 question was marked as a duplicate, I'll add the answer to that here too.
In psycopg3, you can not use in %s with a tuple, like you could in psycopg2. Instead you have to use ANY() and wrap your list inside another list:
conn.execute("SELECT * FROM foo WHERE id = ANY(%s)", [[10,20,30]])
Docs: https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html#you-cannot-use-in-s-with-a-tuple

How to access list of dictionary data with same fields in Python

{
"raw_output": {
"data": {
"sleeps": "[\"{'summaryId': 'x209bf59-59b7574c-594c', 'durationInSeconds': 22860, 'startTimeInSeconds': 1505187660, 'startTimeOffsetInSeconds': -14400, 'deepSleepDurationInSeconds': 7680, 'lightSleepDurationInSeconds': 14100, 'awakeDurationInSeconds': 1080, 'validation': 'AUTO_TENTATIVE'}\", \"{'summaryId': 'x209bf59-59b7574c-6180', 'durationInSeconds': 24960, 'startTimeInSeconds': 1505187660, 'startTimeOffsetInSeconds': -14400, 'deepSleepDurationInSeconds': 7680, 'lightSleepDurationInSeconds': 16140, 'awakeDurationInSeconds': 1140, 'validation': '`AUTO_MANUAL`'}\"]",
},
for example: I would like to access the value of validation of the first dict.
The data embedded in strings needs to be parsed out, ast.literal_eval() can help with that, e.g.:
In []:
import ast
for d in ast.literal_eval(data['raw_output']['data']['sleeps']):
i = ast.literal_eval(d)
print(i['validation'])
Out[]:
AUTO_TENTATIVE
`AUTO_MANUAL`
Your value for sleeps appears to be a string. You need it to be a list. You would may want to replace the string with a list of dictionaries following in order to make it readily index-able. (assuming the dictionary you printed out and posted was stored in a variable called d)
d["raw_output"]["sleeps"] = [eval(k) for k in eval(d["raw_output"]["sleeps"])]
With this done you can now print the value of validation from the first entry as follows.
print(d["raw_output"]["sleeps"][0]['validation'])
As #AChampion pointed out (Epic user name btw) you probably want to
use ast.literal_eval instead of eval.
I hope this helps!
dict["raw_output"]["data"]["sleeps"][0]["validation"] in this way you can access the value of validation.

Generate a list from another list transforming each element on Groovy

I've got the following code on a Controller
def db = new Sql(dataSource)
def rawLines = db.rows("SELECT name FROM LINES")
def lines = []
/*(db.rows returns the values as [NAME:value] */
rawLines.each {
lines.add(it.name)
}
/*Then, use lines */
I can't keep away the impression that there is probably some way to do this in a more elegant way, something similar to a list comprehension in Python:
lines = [ l.name for l in db.rows("SELECT name FROM LINES") ]
Having to declare an empty list and then populate it doesn't seem the best way of doing things...
Is it possible to do something like this, or Groovy doesn't allow it?
Can't you just use the spread operator, and do:
lines = rawLines*.name
(see http://docs.groovy-lang.org/latest/html/documentation/index.html#_spread_operator)
tim_yates' answer is a clean solution when you want to call a method (or property) on each element of list in order to transform it e.g.:
[1,2,3]*.multiply(5)
but if you want to call a method from another object or do something more complex you can use collect:
[1, 2, 3].collect {Math.cos(it * Math.PI)}
Well, If you are using grails, why aren't you simply using the a model class together with the findAll method?
Using plain raw SQL should be done on exceptional cases.

Resources