12👍
You can use values_list(…)
[Django-doc] instead, and specify flat=True
, like:
def get(self, request, format=None):
labels = list(Temperature.objects.using('sensors').values_list('time', flat=True))
temp_values = list(Temperature.objects.using('sensors').values_list('value', flat=True))
# ...
but the above is not safe. A queryset is – unless you specify it – unordered. That means that two queries can result in data that does not "match" in the sense that the first time
value does not per se corresponds to the first value
value, although this might be atypical behavior (in some/most database systems), you typically never want this to happen. It also here results in two queries, which is not efficient.
You can first fetch the values, and then use map
s (or zip
) to make a transpose, like:
from operator import itemgetter
def get(self, request, format=None):
qs = Temperature.objects.using('sensors').values_list('time', 'value')
labels = list(map(itemgetter(0), qs))
temp_values = list(map(itemgetter(1), qs))
# ...
4👍
For this you have to use the ‘values_list’ function instead of ‘values’, and if you only want one field, use flat=True:
temp_values = Temperature.objects.using('sensors').values_list('value', flat=True)
- [Django]-Django shell doesn't respect cache configuration
- [Django]-MongoDB storage along with MySQL XPath features
- [Django]-Cannot urlencode() after storing QueryDict in session
- [Django]-Upload image files with specific directory structure to amazon s3 django
1👍
If I’m understanding your question correctly, I think you’re looking for values_list instead of values
.
Also, you probably don’t need that list()
call in there — it’ll just slow things down and waste memory.
- [Django]-TypeError: add() argument after * must be a sequence, not Subscribers
- [Django]-How to modify django-ckeditor inline styles?
- [Django]-What is the best framework/reusable app for caching model instances (object level cache) in Django?
- [Django]-How to populate database fields when model changes in django