简体   繁体   English

Django Admin中的自定义查询过滤器

[英]Custom query filter in django admin

Here is my models code: 这是我的模型代码:

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)

I want filter all Quote based on characters length, and this is my query in django admin. 我想根据字符长度过滤所有报价,这是我在django admin中的查询。

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"})

However, it returns Programming error more than one row returned by a subquery used as an expression 但是,它返回编程错误不止是用作表达式的子查询返回的一行

Any ideas how to fix? 任何想法如何解决?

What I am trying is to find all Quote s where quote_text length is less than 50 characters 我试图是要找到所有Quote S其中quote_text长度少于50个字符

Say goodbye to extra and say hello to Length 告别extra问好长度

from django.db.models.functions import Length

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

much neater, safer and shorter 更整洁,更安全,更短

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM