auth_user 的自定义模型管理器
我想在 auth user
模型上添加两个额外的管理器,active
和 inactive
,以便为我提供活跃用户或非活跃用户。这就是模型的外观(即使它无效):
from django.contrib.auth.models import User
class ActiveManager(models.Manager):
def get_query_set(self):
return super(ActiveManager, self).get_query_set().filter(active=True)
class InactiveManager(models.Manager):
def get_query_set(self):
return super(InactiveManager, self).get_query_set().filter(active=False)
class User(models.Model):
# user model...
all_users = models.Manager()
objects = ActiveManager()
inactive = InactiveManager()
我应该将其放置在哪里/如何准确地进行查询,例如 User.inactive.all()
?谢谢。
I want to include two extra managers on the auth user
model, active
and inactive
, to give me just active, or just inactive users. This is how the model would look (even if the it is invalid):
from django.contrib.auth.models import User
class ActiveManager(models.Manager):
def get_query_set(self):
return super(ActiveManager, self).get_query_set().filter(active=True)
class InactiveManager(models.Manager):
def get_query_set(self):
return super(InactiveManager, self).get_query_set().filter(active=False)
class User(models.Model):
# user model...
all_users = models.Manager()
objects = ActiveManager()
inactive = InactiveManager()
Where / how exactly would I place this so I can do a query such as User.inactive.all()
? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在 Manager 上使用
contribute_to_class
方法。您将需要这样的东西,而不是您在那里的User
类:我怀疑您在哪里执行此操作并不重要,只要它发生得好且早(在您使用它之前!) - 某处的 models.py 感觉有点正确。
You're going to need to use the
contribute_to_class
method on your Manager. Instead of theUser
class you have there, you will need something like this:I suspect it doesn't matter exactly where you do this as long as it happens nice and early (before you use it!) - a models.py somewhere would feel vaguely right.