Answer the question
In order to leave comments, you need to log in
What is the preferred filter for selecting the last element?
Hello.
Situation: there are 100 forum topics, each topic has 10 comments, each comment has its own author.
Task: display the username of the last person who left a comment in a separate topic.
There is a question about the filter to display the last user from the topic.
Two options:
last_user = item.forumcom_set.latest('user_link').user_link
last_user = item.forumcom_set.all().order_by('-id')[0].user_link
Answer the question
In order to leave comments, you need to log in
Let's see what happens in the first and second cases
def latest(self, field_name=None):
return self._earliest_or_latest(field_name=field_name, direction="-")
def _earliest_or_latest(self, field_name=None, direction="-"):
...
obj = self._clone()
obj.query.set_limits(high=1)
obj.query.clear_ordering(force_empty=True)
obj.query.add_ordering('%s%s' % (direction, order_by))
return obj.get()
def order_by(self, *field_names):
...
obj = self._clone()
obj.query.clear_ordering(force_empty=False)
obj.query.add_ordering(*field_names)
return obj
def __getitem__(self, k):
...
qs = self._clone()
qs.query.set_limits(k, k + 1)
return list(qs)[0]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question