I have a soft-delete user model in Django, where we set is_active
to False.
But one problem I'm running into is needing to filter out is_active
users on every type of content:
Item.objects.filter(user__is_active=False, ...)
Comment.objects.filter(user__is_active=False, ...)
User.objects.filter(is_active=False, ...)
And so-on. Is there some type of Django / Pythonic design pattern I can use here to avoid needing to manually filter out all users every time I query something made by a user, or a current list of users?
CodePudding user response:
You can use ModelManager.
For example:
class ItemManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_active=True)
class Item(models.Model):
.....
objects = ItemManager() # your custom manager
all_objects = models.Manager() # default manager
Now with Item.objects.all()
you will get objects having is_active=True
only.
If you want all the objects then you can use Item.all_objects.all()
CodePudding user response:
https://docs.djangoproject.com/en/4.0/topics/db/managers/
You need to use custom managers and add to model.
You can redefine get_queryset
method to filter is_active.