class CategoryManager(models.Manager): """ A manager that adds an "active()" method for all active categories """ def active(self): """ Only categories that are active """ return self.get_query_set().filter(active=True) class CategoryBase(MPTTModel): """ This base model includes the absolute bare bones fields and methods. One could simply subclass this model and do nothing else and it should work. """ parent = TreeForeignKey(‘self‘, blank=True, null=True, related_name=‘children‘, verbose_name=_(‘parent‘)) name = models.CharField(max_length=100, verbose_name=_(‘name‘)) slug = models.SlugField(verbose_name=_(‘slug‘)) active = models.BooleanField(default=True, verbose_name=_(‘active‘)) objects = CategoryManager() tree = TreeManager() def save(self, *args, **kwargs): """ While you can activate an item without activating its descendants, It doesn‘t make sense that you can deactivate an item and have its decendants remain active. """ if not self.slug: self.slug = slugify(SLUG_TRANSLITERATOR(self.name))[:50] super(CategoryBase, self).save(*args, **kwargs) if not self.active: for item in self.get_descendants(): if item.active != self.active: item.active = self.active item.save() def __unicode__(self): ancestors = self.get_ancestors() return ‘ > ‘.join([force_unicode(i.name) for i in ancestors] + [self.name, ]) class Meta: abstract = True unique_together = (‘parent‘, ‘name‘) ordering = (‘tree_id‘, ‘lft‘) class MPTTMeta: order_insertion_by = ‘name‘
http://www.oschina.net/translate/higher-level-query-api-django-orm
http://www.nanerbang.com/article/34/
这里的貌似也不错
from django.db import models class PublicArticleManager(models.Manager): def get_query_set(self): return super(PublicArticleManager, self).get_query_set().filter(public = True) class Article(models.Model): #... public = models.BooleanField(‘是否发表‘, default = False) objects = models.Manager() public_articles = PublicArticleManager()
http://hunterford.me/django-custom-model-manager-chaining/
时间: 2024-12-21 15:50:19