Django: how do I get a queryset of all users that are staff?
I'm trying:
staff = User.objects.get(is_staff=True)
but get a TypeError:
'User' object is not iterable
get in a queryset is to get specific object value and is not iterable.
user = User.objects.get(id=2)
It gives you user object whose id is 2. There can only be 1 user with id 2
But in your case there can be many user with staff status
staff = User.objects.filter(is_staff=True)
This gives you list of staff. If you are looking for one object then use get if looking for list then use filter.
You can now use this in your template like this
{% for stf in staff %}
{{stf.username}}
{% endfor %}
使用filter
而不是get
。
staff = User.objects.filter(is_staff=True)
The point is when using staff = User.objects.get(is_staff=True)
that you can't be sure that it will return a single user (unless you know for sure).
Probably you might want to add more criteria to narrow down the options to one.
A more safer option is to user filter
, which returns a list of users with matched criteria, without the need to exception-handle objects.get
when things go against the expected
get is used for returning a single object - not a queryset. It will give an error if it returns more than one entry from the database. In your case I am guessing it is returning a single User, and you are trying to iterate over that.
filter is what you want to use. It returns a queryset that can be iterated over.
staff = User.objects.filter(is_staff=True)
for person in staff :
do stuff....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.