kholidfu
kholidfu

Reputation: 74

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.

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 Quotes where quote_text length is less than 50 characters

Upvotes: 2

Views: 463

Answers (1)

e4c5
e4c5

Reputation: 53734

Say goodbye to extra and say hello to Length

from django.db.models.functions import Length

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

much neater, safer and shorter

Upvotes: 3

Related Questions