django admin

时间:2017-03-22 04:28:01

标签: python django django-models django-queryset

这是我的模型代码:

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

但是,它返回编程错误多个用作表达式的子查询返回的行

任何想法如何解决?

我想要的是查找Quote长度小于50个字符的所有quote_text

1 个答案:

答案 0 :(得分:3)

告别extra并向Length

打个招呼
from django.db.models.functions import Length

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

更整洁,更安全,更短