get users except superuser django
To retrieve users in Django, excluding the superuser, you can follow these steps:
- Import the necessary modules:
from django.contrib.auth.models import User
from django.db.models import Q
The first line imports the User model from the django.contrib.auth.models
module, and the second line imports the Q object from the django.db.models
module. The Q object is used for complex queries.
- Construct the query to filter out the superuser:
users = User.objects.filter(~Q(is_superuser=True))
Here, the filter()
method is used on the User model to retrieve all users. The ~Q(is_superuser=True)
argument filters out the superuser by excluding users where the is_superuser
field is True
.
- Access the required user information:
for user in users:
print(user.username)
In this example, we iterate through the users
queryset and print the username of each user. You can access other user fields in a similar manner.
These steps should allow you to retrieve all users in Django while excluding the superuser.