python - 不等于的 Django 管理模型查询 url 字符串
问题描述
我在 postgreSQL 中的两个模型之间有一个简单的 Django ForeignKey 关系。这里的逻辑是 Sample 对象可以选择有一个外键到一种类型的示例控件中。
from django.contrib.postgres.fields import CICharField
from django.db import models
class Sample(models.Model):
controls_applied = models.ForeignKey(SampleControl, null=True,
blank=True,
on_delete=models.SET_NULL)
class SampleControl(models.Model):
id = CICharField(max_length=200, primary_key=True)
在 Sample 的管理员更改列表中,我正在尝试创建过滤器来查询所有或没有具有特定控件的 Samples(在这种情况下,我们将使用 id='runcontrol' 的 SampleControl)。我正在尝试制作特定的 URI 字符串以附加到我的更改列表 url,因为我有其他过滤器正在尝试一起运行。
要使用 获取所有样本controls_applied= 'runcontrol'
,我可以简单地将以下字符串附加到我的 URL(注意对外键 id 的引用):
?controls_applied__id=runcontrol
但如果我想获得所有不受运行控制的样本,那就更复杂了。不知道该怎么做,所以我决定使用“startswith”,它有一个方便的“notstartswith”伴侣,可以做相反的事情。当我使用它时,我看到以下工作:
?controls_applied__id__startswith=runcontrol
然而,逆
?controls_applied__id__notstartswith=runcontrol
给我一个错误:Unsupported lookup 'notstartswith' for CICharField or join on the field not permitted, perhaps you meant startswith or istartswith?
这引出了一个简单的问题:有没有办法在 Django 管理站点上的 URL 的查询字符串中指定 NOT EQUALS?谢谢!
解决方案
我不认为管理员 URL 能够代表查询集exclude
过滤器,除非您创建自己的SimpleListFilter
.
在你的 admin.py 中试试这个:
class WithoutControlListFilter(admin.SimpleListFilter):
title = ('Without Control')
parameter_name = 'without_control'
def lookups(self, request, model_admin):
return (
('runcontrol', ('Run Control')),
)
def queryset(self, request, queryset):
return queryset.exclude(controls_applied=self.value())
class SampleAdmin(admin.ModelAdmin):
list_filter = (WithoutControlListFilter,)
在Django ModelAdmin 文档中有一些关于管理过滤器的信息。
推荐阅读
- java - 在 gradle 文件 android 中为 HTTP 添加什么依赖项;ByteArrayBody、HttpMultipartMode、StringBody 无法解析
- google-apps-script - 对于肯定存在的床单,一直保持错误
- javascript - form.submit(); 不运行形式的动作
- r - “无效的参数类型”通过函数的参数传递 html 颜色
- unity3d - DOTween.To() 何时发生在 Unity 的“事件函数的执行顺序”中
- android - ionic Cordova 构建 android 错误和 gradle 版本兼容性
- c# - 如何阻止我的角色自动上升?
- java - NamedParameterJdbcTemplate - 选择 Id from
- swift5 - 如何通过流从java服务器的printwriter读取字符串到swift客户端
- microservices - 如何在事件溯源中插入静态数据?