Django Query Data

24 views
Skip to first unread message

Brendan Edwards

unread,
May 3, 2014, 8:47:07 PM5/3/14
to django...@googlegroups.com
Hi,
 
I have just started learning Django (been flip flopping between meteor and django, cant decide which to use..) and I am fairly new to web development in general.
 
Basically, I have a query where I am using the code "teecolor = GolfCourseTees.objects.values('Tee_Color').filter(Course_Name=course)" but I want to take the value retrieved form this and use it to make another query before loading the template. When I set color1= teecolor[0] color 1 will show as: {'Tee_Color': u'Blue'}, and I am unsure why this happens. I want to retrieve only the value "blue" in this case.
 
The reason for this is each course has usualy 4-5 tee colors. therefore I will have color1 = teecolor[0], color 2 = teecolor[1] etc.. so that I can insert that into a second query. To do that these values need to be "blue" "black" etc
 
Questions:
 
1) What is the data "{'Tee_Color': u'Blue'}" output "{'Tee_Color': u'Blue'}" called and why does it display like this (I would like to understand and not just insert a given line of code)? I have read the documentation and I am still confused on this.
2) How can I retrieve blue from {'Tee_Color': u'Blue'}? (example code would be helpful)
Brendan
 

C. Kirby

unread,
May 5, 2014, 3:36:43 PM5/5/14
to django...@googlegroups.com
The reason you are getting a dictionary in return is because the call to values() returns a ValueQuerySet, which is an iterable of dictionaries (https://docs.djangoproject.com/en/dev/ref/models/querysets/#values)
In order to get a list of tee colors (eg ['Blue',Green','Red']) you should use a value_list(). values_list usually returns a list of tuple, but if you are only asking for a single field you can give it the flat flag, which flattens the tuples into just the field value. (https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list)

Taken all together, your query should be:
teecolors = GolfCourseTees.objects.filter(Course_Name=course).values_list('Tee_Color', flat=True)

Kirby
Reply all
Reply to author
Forward
0 new messages