Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract only values without key from QuerySet and save them to list

I have problem with getting only values from QuerySet. I have my table:

class Temperature(models.Model):
    id = models.IntegerField(primary_key=True)  # AutoField?
    name = models.TextField(blank=True, null=True)
    value = models.IntegerField(blank=True, null=True)
    time = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'temperature'

and in views.py:

class ChartData(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        labels = list(Temperature.objects.using('sensors').values('time')) 
        temp_values = list(Temperature.objects.using('sensors').values('value'))

        data = {
            "labels": labels,
            "temperature": temp_values,
        }
        return Response(data)

and with console.log() in html file I'm checking values, currently they are:enter image description here

But I want to retrive only value, without key. For e.g. : enter image description here

Any help would be highly appreciated

like image 674
Aleksandra Skoczypiec Avatar asked Nov 26 '25 23:11

Aleksandra Skoczypiec


1 Answers

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 maps (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))
    # ...
like image 189
Willem Van Onsem Avatar answered Nov 28 '25 15:11

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!