views:

70

answers:

2

I have a 7-tuple of tuples as such:

POSSIBILITIES = ((1, "Something"),
                 (2, "Something else"), ...)

Now I have an IntegerField with choices in a model with the possibilities listed above.

class Something(models.Model):

    class Meta:
        ordering = "...?"

    something = models.IntegerField(choices=POSSIBILITIES)

I want the entries in the database to be ordered by the integer in each of the tuples by default. How do I specify that?

+1  A: 

ordering = ('something',) should work. The integer values are what is actually stored for something in the database, so they would be ordered by the integers by default.

Ben James
+2  A: 

This should do the trick:

class Meta:
    ordering = ('something',)

The last comma is important, it is required.

af
For anyone reading this and wondering about the comma, that's how you write a 1-tuple in Python.
Deniz Dogan
Python's use of a trailing comma to differentiate a 1-tuple from a parenthesized expression is a hack. One way to avoid being bit by this is to use a list instead of a tuple. (E.g "ordering = ['something']") I doubt there is any significant performance hit and Django doesn't care, it just wants an iterable. This 1-tuple snag can get particularly irritating if you have a complex fields expression for the Admin edit page.
Peter Rowell