[Django]-Django model default sort order using related table field

39👍

I use django 1.2.7 and instead of connecting ForeignKey.Attribute we should use “__”, so this code will work:

class Meta:
    ordering = ('bar_date', 'related__name', )
👤L.A.

7👍

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

4👍

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',)

4👍

In modern version of django it is:

class Meta:
        ordering = ['word']
👤Atma

0👍

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 … :-))

-2👍

class Question(models.Model):

  question_text=models.CharField(max_length=200)
        class Meta:
    verbose_name_plural="  Question"

class Choice(models.Model):

  question=models.ForeignKey(Question,on_delete=models.CASCADE)
    class Meta:
    verbose_name_plural=" Choice"

Either you can alter the number of spaces before the class name as above or order it using numbers as below:

class Question(models.Model):

  question_text=models.CharField(max_length=200)
        class Meta:
    verbose_name_plural="1.Question"

class Choice(models.Model):

  question=models.ForeignKey(Question,on_delete=models.CASCADE)
    class Meta:
    verbose_name_plural="2.Choice"

Leave a comment