具有模型属性的 Django 管理 search_fields

发布于 2024-09-19 11:31:00 字数 1050 浏览 2 评论 0原文

我正在尝试使用模型中的属性作为 django admin (1.2) 中的字段。

这是我的代码的示例:

class Case(models.Model):
    reference = models.CharField(_(u'Reference'), max_length=70)
    client_read = models.BooleanField(default=0)

    def __unicode__(self):
        return self.case_id

    @property
    def case_id(self):
        """ unique case ID """
        number = (settings.CASE_ID_LENGTH - len(str(self.id))) * "0" + str(self.id)
        return '%(year)s%(unique_id)s' % { 
            'year': self.case_date.strftime("%y"),
            'month': self.case_date.strftime("%m"),
            'unique_id': number}

以及 admin.py 的部分:

class OrderAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
    [...]
    search_fields = ('id','case','req_surname','req_forename','req_company')

我可以将该字段引用为“case”(如示例中给出的那样),但这给了我一个 类型错误:相关字段具有无效的查找: icontains

当然,它以相关字段的方式工作:所以我可以使用 case__id,然后我就可以使用该 id 作为搜索查询。 但这对用户来说有点恼火,因为 caseid 显示不同。

有没有办法像显示的那样使用 case_id 作为搜索查询(年+月+id)?

I'm trying to use a property in my model as a field in django admin (1.2).

Here's an example of my code:

class Case(models.Model):
    reference = models.CharField(_(u'Reference'), max_length=70)
    client_read = models.BooleanField(default=0)

    def __unicode__(self):
        return self.case_id

    @property
    def case_id(self):
        """ unique case ID """
        number = (settings.CASE_ID_LENGTH - len(str(self.id))) * "0" + str(self.id)
        return '%(year)s%(unique_id)s' % { 
            'year': self.case_date.strftime("%y"),
            'month': self.case_date.strftime("%m"),
            'unique_id': number}

and the part of admin.py:

class OrderAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
    [...]
    search_fields = ('id','case','req_surname','req_forename','req_company')

I can refer to the field as 'case' (like given in the example), but this gives me a TypeError: Related Field has invalid lookup: icontains

Of course it's working the way with related fields: so I can use case__id and then I'm able to use the id as search query.
But this is somewhat irritating to the users cause the caseid is shown different.

Is there a way to use the case_id as search query like it's shown (year+month+id)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晒暮凉 2024-09-26 11:31:00

不,您不能以这种方式使用它,因为这只适用于表示数据库中的列的属性,而不适用于属性。实现此目的的唯一方法是使用 contrib.admin.views.main.ChangeList 的子类作为更改列表,并覆盖它的 get_query_set 方法以实现所需的行为!

No you cannot use it that way, because this only works with attributes that represent columns in the database, not with properties. The only way to make this work would be using a subclass of contrib.admin.views.main.ChangeList for the change list and overwrite it's get_query_set method to achieve the desired behaviour!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文