开发者

Django | sort one-to-many relationship on Master's admin page

I have two models:

Folder
  ...

Photo
  folder = models.ForeignKey(Folder)开发者_高级运维

I was wondering if I can add a field to Folder's Admin edit page so that I can order the list of photos that would relate to that folder.


If you are using InlineModelAdmin and development version of django, you can set ordering option and have the photos ordered.

Check the docs: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-options


Yes, this is a common problem with a not so documented fix that I found while trying to solve the same problem.

Specify the FormSet used by the Inline and override get_queryset() in your formset definition.

from django.forms.models import BaseInlineFormSet

class OrderedFormSet(BaseInlineFormSet):
    def get_queryset(self):
        return super(OrderedFormset, self).get_queryset().order_by('-sortfield')

class MyInline(admin.TabularInline):
    model = Item
    formset = OrderedFormSet
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜