简体   繁体   English

django中如何有一个按具有关联的字段过滤的变更列表?

[英]How to have a change list in django that filters by a field having a relation?

Suppose I have two models: 假设我有两个模型:

class Blog(models.Model):
    pass

class Article(models.Model):
    blog = models.ForeignKey(Blog, related_name="articles")

I want to filter only blogs that have an article. 我只想过滤包含文章的博客。 The filter would be something like this: 过滤器将是这样的:

Blog.objects.annotate(article_count=models.Count('articles')).filter(article_count__gt=0)

How can I have the change list at the admin filter like this? 我怎样才能在管理员过滤器中找到这样的更改列表? I tried a few approaches, like custom filterspecs, but had no success. 我尝试了一些方法,例如自定义filterspecs,但没有成功。 The best solution was to use a proxy model and register a separated admin list, like this solution: 最好的解决方案是使用代理模型并注册一个单独的管理员列表,如下所示:

Multiple ModelAdmins/views for same model in Django admin Django管理员中同一模型的多个ModelAdmins /视图

But that doesn't work very well with the permission system. 但这在权限系统上效果不佳。 Any ideas? 有任何想法吗?

There's currently no way, aside from some very painful hacks, to accomplish that. 除了一些非常痛苦的黑客攻击外,目前没有其他方法可以实现这一目标。 Django 1.4 will ship with the ability to create custom filterspecs (see: https://code.djangoproject.com/ticket/5833 ), which will allow you to do stuff like this. Django 1.4将具有创建自定义filterspec的功能(请参阅: https ://code.djangoproject.com/ticket/5833),这将使您能够执行以下操作。

Since this seems to be kind of an edge case (really, how many blogs will ever have zero posts for a significant period of time?) My suggestion would be to just hold out for now, and maybe look into upgrading once 1.4 is released. 由于这似乎是一个极端情况(真的,在相当长的一段时间内,有多少博客的文章数为零?)我的建议是暂时坚持一下,并考虑在1.4发布后进行升级。

If you insist on going down the rabbit hole, you can start here: Custom Filter in Django Admin on Django 1.3 or below 如果您坚持要走小路,可以从这里开始: Django 1.3或更低版本的Django Admin中的Custom Filter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM