如何从Django的查询集中排除非活动用户 [英] how to exclude non-active users from queryset in django
本文介绍了如何从Django的查询集中排除非活动用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从项目中排除非活动用户。
I want to exclude non-active users from my project.
example 1:
url:users/1/friends/ will show all friends of that user.
我只想在朋友列表中显示活跃用户。
I want to show only active users in friend list.
example 2:
url:users/1/friends/ will show all friends of that user.
如果id为1的用户未激活,我不想显示他的任何活动。像他的朋友一样。.他的个人资料...等等
if user with id 1 is not active i don't want to show any activity of him..like his friends..his profile...etc
example 3:
url:users/1/challenge/ will show all friends of that user in post form.
我不想以表格形式显示非活动用户。
i don't want to show non-active users in form.
有没有通用的方法可以执行此操作。因为这是一个很大的项目,我无法在所有地方进行过滤。
is there any generic way to perform this. Because its a big project and I can't make filter everywhere.
表就像:
class User(models.Model):
......
......
friends = models.ForeignKey(User)
推荐答案
您应该使用自定义模型管理器:
You should use a custom Model Manager:
class ActiveUsersManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
return super(ActiveUserManager, self).get_queryset().filter(is_active=True)
class User(models.Model):
is_active = models.BooleanField(default=true)
# first manager is the default and accessible through objects.
active = ActiveUsersManager()
all_users = models.Manager()
active_users = User.objects.all()
all_users = User.all_users.all()
这篇关于如何从Django的查询集中排除非活动用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文