S
S
Sergey Nizhny Novgorod2016-06-21 02:44:58
Django
Sergey Nizhny Novgorod, 2016-06-21 02:44:58

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

Which one is more profitable to use in terms of performance and ideology?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2016-06-21
@Terras

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]

Those. in both cases, the set_limits, clear_ordering, add_ordering methods are applied to the query. They differ only in the force_empty=False/True argument and the field by which you sort (it's not clear why you sort by user_link)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question