views:

1791

answers:

4

Is it possible to set the default sort order for a model to a field from a related model (rather than the integer key) i.e. something that yields a SQL order by clause with a field from both models? If so, how? I can do this via query_by but I can't figure out how to set it by default. Thanks.

class Foo(models.Model):
    name = models.CharField(max_length=50)

class Bar(models.Model):
    related = models.ForeignKey(Foo)
    bar_date = models.DateField()

    class Meta:
        ordering = ('bar_date', 'related.name', )
+2  A: 

Take a look at order-with-repsect-to.

Stuart Childs
+1  A: 

hmm ... I am solving similar thing while upfactoring old django application, written before qs-rf, where "dot" notation was probably used ??? ... it took me few hours to diclose "something" and I am still NOT sure, but ... try to replace dot with "__" (double underscores), this can help, .. In fact, curentlly, I still HOPE TOO :-)))

@stuart: for "order_with_respect_to", I readed something about automatically added physical model field into child table ... I dont completelly understand how things are here ... IMHO documentation is very bad about ordering syntax, howgh!

no comment :-) http://code.djangoproject.com/ticket/8975

anyway, I like Django, yet ... :-))

falken007
A: 

As an alternative to order_with_respect_to (which only supports one field), you can use a custom manager to provide the ordering. This also allows you to order on multiple fields in Foo and to still have a normal Bar.objects manager. You'll have to test to see if the Meta.ordering or the custom manager ordering is applied first.

class FooSortedManager(models.Manager):
    def get_query_set(self):
        return super(FooSortedManager, self).get_query_set().order_by('foo__name')

class Foo(models.Model):
    name = models.CharField(max_length=50)

class Bar(models.Model):
    related = models.ForeignKey(Foo)
    bar_date = models.DateField()

    foo_sorted = FooSortedManager()

    class Meta:
        ordering = ('bar_date',)
mattkemp