7

My code which created the list is:

choices = []
for bet in Bet.objects.all():
    #...
    #Here is code that skip loop if bet.choice exist in choices[]
    #...
    temp = {
        'choice':bet.choice,
        'amount':bet.sum,
        'count':bets.filter(choice=bet.choice).count()}
    choices.append(temp)

choices.sort(key=attrgetter('choice'), reverse=True)
choices.sort(key=attrgetter('amount'), reverse=True)
choices.sort(key=attrgetter('count'), reverse=True)

I have to sort by list because model orderby() cant sort by count(),can it?

Akshay Hazari
  • 3,186
  • 4
  • 48
  • 84
Zero0Ho
  • 166
  • 1
  • 1
  • 9
  • Please post (and read) the complete error. – skyking Dec 02 '15 at 12:39
  • @skyking: `AttributeError: 'dict' object has no attribute 'choice'`.. – Martijn Pieters Dec 02 '15 at 12:40
  • This means that the `dict` object doesn't have an attribute `choice`. Actually reading the error message and thinking a bit about that is a good start when trouble-shooting. It turns out that it's the elements of the list that lacks the attribute. – skyking Dec 02 '15 at 12:53

1 Answers1

19

Your dictionaries have no choice, amount or count attributes. Those are keys, so you need to use an itemgetter() object instead.

from operator import itemgetter

choices.sort(key=itemgetter('choice'), reverse=True)
choices.sort(key=itemgetter('amount'), reverse=True)
choices.sort(key=itemhetter('count'), reverse=True)

If you want to sort by multiple criteria, just sort once, with the criteria named in order:

choices.sort(key=itemgetter('count', 'amount', 'choice'), reverse=True)

You probably want to have the database do the sorting, however.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Oh! It's work now. and I have more question I try this before choices = sorted(choices.items(), key=itemgetter(1)) but it didn't work – Zero0Ho Dec 02 '15 at 12:46
  • @ZeroOHo: that's because `choices` is a **list** of dictionaries. Lists don't have a `.items()` method. – Martijn Pieters Dec 02 '15 at 12:53