Well this is a simple question i want to filter two elements sorted reverse by date.
The model is:
Class ModelName(models.Model):
usr = models.ForeignKey(UserProfile)
created = models.DateTimeField(default=datetime.datetime.now)
The way i do it is:
ModelName.object.filter(param=param).order_by('-created')[:2]
As per my understanding what i think happens behind the scene is:
-
All the objects from ModelName are filtered
-
they are sorted
-
only two of them are selected.
Maybe i am wrong, if not then how can i filter only last two elements based on the date.
Yes, but that’s done by the database, not by python. See querysets are lazy. So, that actually works pretty well since all this python:
Will be converted to SQL when qs records are accessed (ie. for model in qs …)