I'd like to extend the FlatPage model in Django so that I can implement searching within its field. That's what I've done:
models.py:
from django.db.models import Q
from django.contrib.flatpages.models import FlatPage
class FlatPageManager(models.Manager):
def search(self, query=None):
qs = self.get_queryset()
if query is not None:
or_lookup = (Q(title__icontains=query) |
Q(content__icontains=query)
)
qs = qs.filter(or_lookup).distinct()
return qs
class MyFlatPage(FlatPage):
objects = FlatPageManager()
views.py:
class SearchView(ListView):
[...]
def get_context_data(self, *args, **kwargs):
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self):
request = self.request
query = request.GET.get('q', None)
if query is not None:
flatpage_results = MyFlatPage.objects.search(query)
qs = sorted(queryset_chain,
key=lambda instance: instance.pk,
reverse=True)
return qs
The above search method works for other models I have, so it should also work for MyFlatPage. Nevertheless, I get no results coming from that query. Am I missing something?
Update 1
What is empty is the whole MyFlatPage list:
>>> MyFlatPage.objects.all()
<QuerySet []>
There is two common types for django models inheritance: the proxy-models and as a new models.
If you want to use FlatPage
table as a table for new model - MyFlatPage
you have to define MyFlatPage
as a proxy one by adding proxy = True
flag in Meta
:
class MyFlatPage(FlatPage):
class Meta:
proxy = True
In other case you will have another table for MyFlatPage
.