Pradeep Agnihotri
Pradeep Agnihotri

Reputation: 371

how to exclude non-active users from queryset in 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.

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.

Tables are like:

class User(models.Model):
  ......
  ......
  friends = models.ForeignKey(User)

Upvotes: 2

Views: 4268

Answers (3)

Artem Bernatskyi
Artem Bernatskyi

Reputation: 4677

You can use Creating a manager with QuerySet methods

can be used to create an instance of Manager with a copy of a custom QuerySet’s methods

class UserQuerySet(models.QuerySet):
    def active(self):
        return self.filter(is_active=True)

class User(models.Model):
    is_active = models.BooleanField(default=true)

    objects = UserQuerySet.as_manager()

And use it simply like this

User.objects.active()

For custom users (AbstractUser) you need this solution
It is based on this answer

from django.db.models import QuerySet
from django.contrib.auth.models import AbstractUser, UserManager


class UserQuerySetManager(UserManager):
    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            # don't delegate internal methods to the queryset
            if attr.startswith('__') and attr.endswith('__'):
                raise
            return getattr(self.get_query_set(), attr, *args)

    def get_query_set(self):
        return self.model.QuerySet(self.model, using=self._db)


class User(AbstractUser):
    objects = UserQuerySetManager()


    class Meta:
        permissions = (
            ('view_all_managers', 'View All Managers'),
        )

    class QuerySet(QuerySet):
        def active(self):
            return self.filter(is_active=True)

Upvotes: 0

Yossi
Yossi

Reputation: 12110

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

Upvotes: 7

Maxime Lorant
Maxime Lorant

Reputation: 36161

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

Upvotes: 1

Related Questions