Django 没有对象匹配给定的查询,但它应该

Django no object matches the given query but it should

我遇到以下问题我的数据库不为空并且有我需要的记录。但是当我查询数据库时,它说没有匹配给定查询的对象。我使用 django-channels 从 websocket 中查询数据库,我的数据库是 postgreSQL。

我知道还有其他关于此的问题,我调查了它们,但它们都是关于空数据库或错误的 url slug,这不是我的情况,也无济于事我有任何东西

对应代码如下:

@channel_session_user_from_http
def ws_receive(message):
    username = message.user.username
    print(username)
    text = json.loads(message['text']).get('text')
    # Use my algorithm here
    score = score_argument.get_rating(text)
    # find the room with our users

    current_room = get_object_or_404(PairUsers, Q(username_a=username) | Q(username_b=username))

    # current_room = PairUsers.objects.filter(Q(username_a=username) | Q(username_b=username)).first()

    # check which user you got and send the message to the other
    if current_room.username_b == username:
        current_room.score_b = score
        other_channel = Channel(current_room.reply_channel_a)
        message.reply_channel.send({'text': text})
        other_channel.send({'text': text})
    else:
        current_room.score_a = score
        other_channel = Channel(current_room.reply_channel_b)
        message.reply_channel.send({'text': text})
        other_channel.send({'text': text})

我注意到的另一件事是 print(username) 不打印任何内容,它只是跳过这一行。我在不同的函数中使用了 message.user.username 所以我确定它应该 return 用户名

回溯:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35\lib\site-packages\channels\worker.py", line 119, in run
    consumer(message, **kwargs)
  File "C:\Program Files (x86)\Python35\lib\site-packages\channels\sessions.py", line 180, in inner
    result = func(message, *args, **kwargs)
  File "C:\Program Files (x86)\Python35\lib\site-packages\channels\auth.py", line 73, in inner
    return func(message, *args, **kwargs)
  File "C:\Program Files (x86)\Python35\lib\site-packages\channels\sessions.py", line 64, in inner
    return func(message, *args, **kwargs)
  File "C:\Program Files (x86)\Python35\lib\site-packages\channels\auth.py", line 89, in inner
    return func(message, *args, **kwargs)
  File "C:\Users\nithe\Desktop\debateit\play\consumers.py", line 51, in ws_receive
    current_room = get_object_or_404(PairUsers, Q(username_a=username) | Q(username_b=username))
  File "C:\Program Files (x86)\Python35\lib\site-packages\django\shortcuts.py", line 93, in get_object_or_404
    raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
django.http.response.Http404: No PairUsers matches the given query.

message.user.username 看起来是 None,你的查询当然会失败。这个问题不是数据库问题(还),它是 channels 相关的。
尝试打印您的 message.user.__dict__,看看它是否与您期望的对象匹配。