Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make Django admin reflect a hierarchy of models?

Assume a Django application with a few models connected by one-to-many relationships:

class Blog(models.Model):
    ...

class Post(models.Model):
    blog = models.ForeignKey(Blog)
    ...

class Comment(models.Model):
    post = models.ForeignKey(Post)
    ...

Conceptually, they form a hierarchy, a tree-like structure. I want the Django admin to reflect that. In particular:

  1. in a changelist of posts, every post should have a link to the changelist of corresponding comments;
  2. similarly, a post’s edit page should link to the changelist of comments from the top-right buttons area;
  3. when I open that list of related comments, it needs to reflect the relationship in the breadcrumbs (something like: Posts › “Hello world” › Comments) and, ideally, also in the URL (post/123/comment/).

This should of course also apply to the other levels of the hierarchy.

Number 1 is pretty easy with a custom list_display entry and using the ?post__id= query to the comments changelist. But this is little more than a hack. Generally Django assumes my three models to be independent, top-level entities.

Is there a straightforward way to accomplish this? I guess I could override a bunch of templates and AdminModel methods, but perhaps there is a better solution for what seems like a common situation?

like image 677
Vasiliy Faronov Avatar asked Feb 26 '13 15:02

Vasiliy Faronov


1 Answers

Are you sure you are not just looking at Django Admin Inline Models ?

There is no way that an automated admin will pick up your relationships, because in an RDBS there can be any number of foreign keys / one to one / many to many relations, and Django does not have a customized hierarchical behavior built in.

You can indeed edit the breadcrumb customizing an admin template if you want.

For relations you might also be interested into django MPTT that allows to make hierarchical model instances. Also see this question: Creating efficient database queries for hierarchical models (django) in that respect.

like image 110
Stefano Avatar answered Sep 17 '22 02:09

Stefano