简体   繁体   中英

Why does filtering a QuerySet behave differently for user vs. superuser?

When logged in as my superuser, 'admin', I'm able to filter a QuerySet by any field. However when I am logged in as a regular user I'm only able to filter by the field 'user'. Trying to filter by any other field returns an empty list.

class Question(models.Model):

    user = models.ForeignKey(User, default=1)
    verb = models.ForeignKey(Verb)
    voice = models.ForeignKey(Voice)
    ...

This works fine:

def next_question(request):
    user = request.user
    q = Question.objects.filter(user=user)

This works fine when logged in as a superuser but fails as a regular user ( myverb is an instance of my Verb model):

def next_question(request):
    user = request.user
    q = Question.objects.filter(user=user, verb=myverb)

I'm new to Django (though not to Python) so am I missing some kind of permission that I need to set for regular users which would fix this behaviour?

Edited to add images showing the items in the database

Example question for superuser, 'admin':

管理员的示例对象

Example question for user 'jamie':

杰米的示例对象

There is no difference between superuser and regular user in this ORM query.

You simply don't have any Question instances with both myverb verb field and request.user user field.

There is no difference. The super user is also a normal user.

Depending on what the value of the user variable is set to at the time (I assume it's the currently logged in user) You could interpret your query as this: all questions where the related user is the currently logged in user.

Therefore if you see no results when you are logged in as someone else it is because you really don't have any questions you are associated with.

If you are sure that you should have results it may be that your user variable is not set to what you think it is. Make sure it's value is correct.

Ie user = request.user

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM