In a Django UserProfile model, I am trying to do the following:
class UserProfile(models.Model):
...
def recent_activity(self):
followed_users = Followed.objects.filter(user=self.id).order_by("-when")
...
items = [self]
for f in followed_users:
items.append(f)
...
sorted(items,key=lambda item: item.getDate)
return items[:7]
The code is supposed to return a user’s “recent activity” by pulling together a number of different actions they can do and then sorting them by date.
Each model implements a “getDate” method which returns the date to sort by.
The code:
- Gets a QuerySet of users that the user has “followed” (I am using a table called Followed to store the fact that user x follows user y).
- Creates a list containing the UserProfile object in question.
- Add each Followed object to the list.
- Sort the list by the last edit date.
- Return the most recent n items (7 in the above).
I thought this was a neat way of implementing it. But no matter what I do, Python seems to refuse the correctly sort that list. It seems to sort every type of recent activity correctly except for the UserProfile – which seems to stay wherever I originally put it in that list after calling sorted. It doesn’t fail in any way, it just doesn’t return a correctly sorted list!
I’ve probably missed something simple… but I would expect either Python to complain that an object’s method cannot sort a list that contains the object itself, OR for the list to be correctly sorted. I was a bit surprised that it did neither.
Can anyone tell me where I’ve gone astray?
Thanks.
The issue is that
sorteddoes not sort in-place.You have probably read that
list.sort()does sort in-place. Butsorted()actually returns the sorted list – but you are not assigning it to anything, so it just gets thrown away. Either usesort(), or assign the result to something.(Plus, you’ll need to actually call
getDate, as Marcin points out.)