how to exclude non-active users from queryset in django

后端 未结 3 594
借酒劲吻你
借酒劲吻你 2021-01-22 06:52

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 a

3条回答
  •  走了就别回头了
    2021-01-22 07:25

    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()
    

提交回复
热议问题