Django 经理
我有以下模型代码:
from django.db import models
from categories.models import Category
class MusicManager(models.Manager):
def get_query_set(self):
return super(MusicManager, self).get_query_set().filter(category='Music')
def count_music(self):
return self.all().count()
class SportManager(models.Manager):
def get_query_set(self):
return super(MusicManager, self).get_query_set().filter(category='Sport')
class Event(models.Model):
title = models.CharField(max_length=120)
category = models.ForeignKey(Category)
objects = models.Manager()
music = MusicManager()
sport = SportManager()
现在通过注册 MusicManager() 和 SportManager() 我可以调用 Event.music.all() 和 Event.sport.all() 查询。但如何创建 Event.music.count() ?我应该在 MusicManager 的 count_music() 函数中调用 self.all() 来仅查询具有“音乐”类别的元素,还是仍然需要先过滤它们以搜索类别?
I have the following models code :
from django.db import models
from categories.models import Category
class MusicManager(models.Manager):
def get_query_set(self):
return super(MusicManager, self).get_query_set().filter(category='Music')
def count_music(self):
return self.all().count()
class SportManager(models.Manager):
def get_query_set(self):
return super(MusicManager, self).get_query_set().filter(category='Sport')
class Event(models.Model):
title = models.CharField(max_length=120)
category = models.ForeignKey(Category)
objects = models.Manager()
music = MusicManager()
sport = SportManager()
Now by registering MusicManager() and SportManager() I am able to call Event.music.all() and Event.sport.all() queries. But how can I create Event.music.count() ? Should I call self.all() in count_music() function of MusicManager to query only on elements with 'Music' category or do I still need to filter through them in search for category first ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将管理器视为查询的“起点” - 您可以继续链接过滤器,就像从默认管理器开始一样。
例如,
Event.objects.filter(category='Music').filter(title='Beatles Concert')
在功能上等同于Event.music.filter(title='Beatles Concert') ')
因此,正如 Daniel 所说,您实际上不需要做任何特殊的事情,只需选择一个自定义管理器而不是
对象
,然后从那里开始。You can think of a manager as a 'starting point' for a query - you can continue to chain filters just as if you'd started out with the default manager.
For example,
Event.objects.filter(category='Music').filter(title='Beatles Concert')
is functionally equivalent toEvent.music.filter(title='Beatles Concert')
So, as Daniel says, you don't really need to do anything special, just choose one of your custom managers instead of
objects
and go from there.您不需要执行任何操作(并且您的
count_music
方法是不必要的)。count()
方法将使用get_query_set
定义的现有查询。You don't need to do anything (and your
count_music
method is unnecessary). Thecount()
method will use the existing query as defined byget_query_set
.