How can I create more than one ModelAdmin for the same model, each customised differently and linked to different URLs?
Let's say I have a Django model called Posts. By default, the admin view of this model will list all Post objects.
I know I can customise the list of objects displayed on the page in various ways by setting variables like list_display or overriding the queryset
method in my ModelAdmin like so:
class MyPostAdmin(admin.ModelAdmin):
list_display = ('title', 'pub_date')
def queryset(self, request):
request_user = request.user
return Post.objects.filter(author=request_user)
admin.site.register(MyPostAdmin, Post)
By default, this would be accessible at the URL /admin/myapp/post
. However I would like to have multiple views/ModelAdmins of the same model. e.g /admin/myapp/post
would list all post objects, and /admin/myapp/myposts
would list all posts belonging to the user, and /admin/myapp/draftpost
might list all posts that have not yet been published. (these are just examples, my actual use-case is more complex)
You cannot register more than one ModelAdmin for the same model (this results in an AlreadyRegistered
exception). Ideally I'd like to achieve this without putting everything into a single ModelAdmin class and writing my own 'urls' function to return a different queryset depending on the URL.
I've had a look at the Django source and I see functions like ModelAdmin.changelist_view
that could be somehow included in my urls.py, but I'm not sure exactly how that would work.
Update: I've found one way of doing what I want (see below), but I'd still like to hear other ways of doing this.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…