Django Query using .order_by() and .latest()

Viewed 79744

I have a model:

class MyModel(models.Model):
   creation_date = models.DateTimeField(auto_now_add = True, editable=False)

   class Meta:
      get_latest_by = 'creation_date'

I had a query in my view that did the following:

instances = MyModel.objects.all().order_by('creation_date')

And then later I wanted instances.latest(), but it would not give me the correct instance, in fact it gave me the first instance. Only when I set order_by to -creation_date or actually removed the order_by from the query did .latest() give me the correct instance. This also happens when I test this manually using python manage.py shell instead of in the view.

So what I've done now is in the Model's Meta I've listed order_by = ['creation_date'] and not used that in the query, and that works.

I would have expected .latest() to always return the most recent instance based on a (date)(time) field. Could anyone tell me whether it's correct that .latest() behaves strangely when you use order_by in the query?

4 Answers

This worked for me

latestsetuplist = SetupTemplate.objects.order_by('-creationTime')[:10][::1]

if we have the value of id or date

post_id = BlogPost.objects.get(id=id)
try:
   previous_post = BlogPost.objects.all().order_by('id')[post_id.id-2:post_id.id-1]
except:   
   previous_post = None
try:
   next_post = BlogPost.objects.all().order_by('id')[post_id.id:post_id.id+1]
except:
  next_post = None

it worked for me, even if an id is missing it picks next or previous value to that

Related