how to exclude non-active users from queryset in django

后端 未结 3 592
借酒劲吻你
借酒劲吻你 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:21

    If you want to exclude non-active users from a queryset you can use the following filter:

    YourModel.objects.exclude(friend__is_active=False)
    
    # or 
    YourModel.objects.filter(friend__is_active=True)
    

    Where friend is a ForeignKeyField to a User model object in YourModel.

    If you want a more general solution, you can use a ModelManager:

    class ActiveUsersOnlyManager(models.Manager):
        def get_queryset(self):
            return super(ActiveUsersOnlyManager, self).get_queryset().filter(is_active=True)
    
    
    class User(models.Model):
        is_active = models.BooleanField(default=true)
        friends = models.ForeignKey(User)
        # first manager is the default and accessible through objects.
        objects = ActiveUsersManager()
    

提交回复
热议问题