views:

16

answers:

2

I have the datetime filled with auto_now=True
Database is mysql.
Range queries won't work for me directly.
Is there any one liner for this?

For simplicity, how can I get 10 rows with highest values for a field(let it be Integerfield) ?

A: 

order by the field in descending order and limit to 10?

ORDER BY fieldname DESC LIMIT 10
Rob Cooney
+1  A: 

For model Model with integer field field, this should work:

top10 = Model.objects.order_by('-field')[:10]

If you want django to have an index on the field, you need to define it in the model with db_index option:

class Model(models.Model):
    field = IntegerField(db_index=True)

Regular database index should work even if your asking for the highest values.

che
Is there a more efficient way of doing this since this will sort the whole table first which is expensive for a large table?
Rohit
You just need to add index to the table, MySQL will use it automatically.
che