简体   繁体   中英

How to retrieve value from queryset in django?

I am trying to retrieve different .values() from query sets but am having an issue with it returning the proper values. How to write my model so that I can retrieve attributes using the .values() method?

I have tried to change the model's __str__ method to return a dictionary but that does not work or I am doing it wrong.

class Settings(models.Model):
    bb_bonus_qualify = models.CharField(max_length=16, default=38.00)
    service_breakpoint = models.CharField(max_length=16, default=1700.00)

    def __str__(self):
        return '%s: %s, %s: %s' % (
            'bb_bonus', self.bb_bonus_qualify, 'service_breakpoint', self.service_breakpoint)

I would like to say Settings.objects.last().values('bb_bonus') and be returned the value which is self.bb_bonus_qualify . The common error I seem to get is: AttributeError: 'Settings' object has no attribute 'values'

The problem here is that your .last() will retrieve the last Settings object. You thus will call .values('bb_bonus') on the Settings object. Since a model has no .values(..) method, it will thus not return anything.

You can however retrieve the value of a certain column from a queryset, with:

Settings.objects.last()

We here thus use .values_list(..) [Django-doc] , this accepts the names of the columns as parameters. It will then usually return a QuerySet of lists with these values. But if you specify one column; then, as the documentation says:

If you only pass in a single field, you can also pass in the flat parameter. If True , this will mean the returned results are single values , rather than one-tuples.

So that means we create a QuerySet of singular values, and we then will retrieve the last entry of that queryset. Note that we do not fetch all the elements from the queryset, the .last() is "injected" in the query we perform on the database, so the result is the scalar value of that column for the last record.

The .values_list(..) thus needs to be performed before the .last() , since otherwise you are talking to a Settings object, not to a QuerySet .

AFAIK __str__.values()无关 - 这里的问题是您需要获取特定项目之前指定值,而不是相反:

Settings.objects.values('bb_bonus').last()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM