I need to filter database by default every time that I see it (when I save changes or when I open database first time). Can anybody tell me how to do it?
+3
A:
This is possible with custom custom Managers:
Say you have a class called Book
:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
And you want the admin pages for book objects to only show books by Roald Dahl, then you can add a custom manager:
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager()
dahl_objects = DahlBookManager()
Then you just need to specify that your ModelAdmin
should use the dahl_objects
manager, which is explained here.
Dominic Rodger
2010-02-03 15:07:26
A:
here is my modes.py:
from django.db import models
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(processed=False)
class Book(models.Model):
book_name = models.CharField('book',max_length=1000,null=True, blank=True)
url = models.CharField(max_length=1000,null=True, blank=True)
processed = models.BooleanField('Done',)
def __str__(self):
return u'%s' % (self.book_name)
def url1(self):
return '<a href="%s">%s</a>' % (self._url, self.url)
site_url1.allow_tags = True
class Admin:
pass
class Meta:
db_table = 'books'
objects = models.Manager()
dahl_objects = DahlBookManager()
here is my admin.py:
from django.contrib import admin
from mybooks.booksdb.models import Book
from django import forms
admin.autodiscover()
class BookAdmin(admin.ModelAdmin):
def queryset(self,request):
qs=self.model.objects.get_query_set()
ordering = self.ordering or ()
if ordering:
qs=qs.order_by(*ordering)
return qs
....
No filter by default. Where is my miss?
Gennadich
2010-02-03 16:03:04
To use the DahlBookManager in the admin, set `qs=self.model.dahl_objects.get_query_set()` in the `queryset` method.
Alasdair
2010-02-03 16:39:03
Thank you. It works with your correctives
Gennadich
2010-02-04 07:44:14