Django:在 Django Admin 中过滤或显示模型方法
我有一个带有到期日期字段的模型。
我想设置一个管理过滤器,允许用户在“未过期”和“任何”之间切换。
模型方法是相当简单的日期比较,没问题。
然而,在 AdminForm 中将其分配为字段或过滤器参数并不是自动的。
这样的事情可能吗?如果不可能,明智的解决方法是什么...
我什至愿意接受某种自动删除过期行的方式,但我不知道如何开始这条路。
I have a model with an expiration DateField.
I want to set up an Admin filter that will allow the user to toggle between "Not Expired" and "Any".
The model method is quite a simple Date comparison, no problem.
However assigning this as a field or filter parameter in the AdminForm is not automatic.
Is such a thing possible, and if not, what would be a wise work-around...
I would even be open to some sort of automated deletion of Expired rows, but I don't know how to start down that path.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过为其注册两个
ModelAdmin
类,在管理站点上包含该模型两次。您可以重写ModelAdmin
的queryset()
方法来自定义显示哪些实例。请注意,您需要定义一个模型代理并在第二个ModelAdmin
类中使用它,否则 Django 会抱怨注册同一模型两次。models.py
admin.py
您还可以为模型定义自定义管理器,以在管理之外获得相同的过滤,而不是自定义
ModelAdmin.queryset
。另请参阅
You could include the model twice on the admin site by registering two
ModelAdmin
classes for it. You can override thequeryset()
method of theModelAdmin
to customize which instances are shown. Note that you need to define a model proxy and use that in the secondModelAdmin
class, otherwise Django complains about registering the same model twice.models.py
admin.py
Instead of customizing
ModelAdmin.queryset
you could also define custom managers for the models to get the same filtering outside admin as well.See also