首页 > 解决方案 > 不等于的 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='runco​​ntrol' 的 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?谢谢!

标签: pythondjangourldjango-viewsdjango-admin

解决方案


我不认为管理员 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 文档中有一些关于管理过滤器的信息。


推荐阅读