如何设置django管理员订购字段?

时间:2017-04-21 08:51:18

标签: python django

admin.py

class MovieItemInline(AjaxSelectAdminTabularInline):
    model = MovieItem
    ordering = ['-date']


class MovielistAdmin(ModelAdminBase, AjaxSelectAdmin):
    inlines = (MovieItemInline, )


admin.site.register(Movielist, MovielistAdmin)

models.py

class MovieItem(Model):
    title = CharField(default="")
    view_number = IntegerField(default=0)
    price = IntegerField(default=0)
    date = IntegerField(default=0)


class Movielist(Model):
    title = CharField(default="")
    display_order = CharField(default="date")

MovieItemInline是MovielistAdmin的内联属性, 我想对MovieItem进行排序,例如, 如果Movielist.display_order等于" date",则按MovieItem.date排序MovieItem。 如果Movielist.display_order等于" price",则按MovieItem.price排序MovieItem。 如果Movielist.display_order等于" view_number",则按MovieItem.view_number对MovieItem进行排序。 我该怎么办? django支持吗?

1 个答案:

答案 0 :(得分:1)

您可以覆盖MovieItemInline类内的get_ordering方法。

from django.urls import resolve

def get_ordering(self, request):
    # get Movielist object instance from request
    object_id = resolve(request.path).args[0]

    # retrieve Movielist object 
    movie_list = MovieList.objects.get(id=object_id)

    # modify ordering based on movie_list display_order value
    if movie_list.display_order == 'date':
        return ['-date']
    elif movie_list.display_order == 'price':
        return ['-price']view_number
    elif movie_list.display_order == 'view_number':
        return ['-view_number']

    # fallback value if non of the above match
    return ['-title']