gpt4 book ai didi

python - django admin 中的自定义查询过滤器

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:11 25 4
gpt4 key购买 nike

这是我的模型代码:

class Quote(models.Model):
"""Quote model."""
quote_text = models.TextField(unique=True)
author = models.ForeignKey(Author)
topic = models.ForeignKey(Topic)
tags = models.ManyToManyField(Tag)
language = models.ForeignKey(Language)
hit = models.IntegerField(default=0)
published = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

我想根据字符长度过滤所有报价,这是我在 django 管理中的查询。

class QuoteCountFilter(admin.SimpleListFilter):
"""Filter based on quote_text characters count."""
title = _('Quote Text Char Count')
parameter_name = 'quotelength'

def lookups(self, request, model_admin):
return (
('lessthan50', _('Less than 50')),
('morethan50', _('More than 50')),
)

def queryset(self, request, queryset):
if self.value() == 'lessthan50':
return queryset.extra(select={"val": "SELECT id FROM web_quote WHERE character_length(quote_text) < 50"})

但是,它返回编程错误超过一行由用作表达式的子查询返回

有什么解决办法吗?

我正在尝试的是找到所有 Quote,其中 quote_text 长度小于 50 个字符

最佳答案

告别extra,向Length问好

from django.db.models.functions import Length

queryset.annotate(len=Length('quote_text').filter(len__lt=50)

更简洁、更安全、更短

关于python - django admin 中的自定义查询过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42942751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com