holmeswatson
holmeswatson

Reputation: 995

Order by created_at date Django

Im trying to order the 'records' in this model by their creation date/time, but am running into issues.

class MyModel(models.Model):     
  created_at = models.DateTimeField(auto_now_add=True)

  class Meta:
    order_with_respect_to = 'created_at'

I'm getting the following error when I try to run syncdb

AttributeError: 'NoneType' object has no attribute 'to'

Any help appreciated

Upvotes: 2

Views: 3750

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

That's not what order_with_respect_to is for - it's for marking a model as ordered with regard to a related model. Personally, I've never had an occasion to use it so I can't really speak from experience about it - except to say that it's not how you do a simple date ordering.

To order by creation time, use the ordering meta attribute instead:

 class MyModel(models.Model):
     created_at = models.DateTimeField(auto_now_add=True)

     class Meta:
         ordering = ['created_at']

In strict point of fact, you don't absolutely have to declare this. If you don't declare any other ordering, either on your model or your query, results will be sorted by their PK. And by default, PKs will be an auto-incrementing series so objects will be implicitly sorted by their creation order. But if you actually care about the sort order, it's best to be explicit rather than rely on that side effect of ascending PKs.

Upvotes: 5

Related Questions