Skip to content
Advertisement

Django Filter for Model function

I am trying to filter through a TextField where I have stripped it of its HTML tags. However, it gives me this error: “Cannot resolve keyword ‘search’ into field.” Here is my code:

models.py

class Entry(models.Model):
  body = models.TextField()
  
  def search_body(self):
    tags = re.compile('<.*?>')
    cleantext = re.sub(tags, '', self.body)
    return cleantext

views.py

from django.db.models import Q
from .models import Entry
...

def search_list(request, query=None):
  search = "search"
  entrys = Entry.objects.filter(status="publish").filter(Q(search_body__icontains=search)).distinct()

Is there a way to do this?

Advertisement

Answer

I just found a way to get what I’m aiming at. All I have to do is to override the “save” function, as so:

    def save(self, *args, **kwargs):
        self.search_body = clean_text(self)
        super().save(*args, **kwargs)

Thanks for your help.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement