6

假设一个 Django 应用程序具有通过一对多关系连接的几个模型:

class Blog(models.Model):
    ...

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

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

从概念上讲,它们形成了一个层次结构,一个树状结构。我希望 Django 管理员反映这一点。尤其:

  1. 在帖子的变更列表中,每个帖子都应该有一个指向相应评论变更列表的链接;
  2. 同样,帖子的编辑页面应该链接到右上角按钮区域的评论更改列表;
  3. 当我打开相关评论列表时,它需要反映面包屑中的关系(例如:帖子 › “Hello world” › 评论),理想情况下,也反映在 URL ( post/123/comment/) 中。

这当然也应该适用于层次结构的其他级别。

list_display使用自定义条目并使用?post__id=对评论更改列表的查询非常容易。但这只不过是一种黑客行为。通常 Django 假设我的三个模型是独立的顶级实体。

有没有一种简单的方法可以做到这一点?我想我可以覆盖一堆模板和AdminModel方法,但对于看似常见的情况,也许有更好的解决方案?

4

2 回答 2

1

这是一种常见的情况吗?考虑一个模型可以有几乎无限数量的外键关系这一事实,更不用说反之亦然。管理员如何“知道”如何在不进行自定义的情况下以用户需要的方式表示这些数据?

One would suggest you are used to work with content management systems rather than webframeworks (no pun intended). It's important to notice Django isn't a cms, but a webframework you can built on top of as you see fit. In a nutshell: 'Django is rather clueless and unaware of contextual requirements'.

Although the admin is quite a beast out-of-the-box, it can be hard to customize. There have been quite some discussions whether it should even be part of core. I can only suggest, if customizing things tends to get hacky, you should probably write your own 'admin', it's not that hard.

于 2013-02-26T16:53:47.350 回答
0

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.

于 2013-02-26T17:38:33.497 回答