嗨,我正在django上的聊天应用程序与django频道工作,我试图在这里查询用户的所有第一个消息,当我做
user.message_set.all()
it is throw
AttributeError at /
'User' object has no attribute 'message_set'
完整回溯:
Traceback (most recent call last):
File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/__neeraj__/Documents/chat/home/views.py", line 10, in index
print(i.messages_set.all())
AttributeError: 'User' object has no attribute 'message_set'
我models.py
class Message(models.Model):
sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender")
receiver = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="receiver"
)
text = models.CharField(max_length=2000)
created_on = models.DateTimeField(auto_now=True)
my view:
def index(request):
users = User.objects.all()
context = {"users": users}
for user in users:
print(user.message_set.all())
return render(request, "index.html", context=context)
这是因为我在消息表上有用户模型的双外键引用吗?
您指定的related_name
非常不正确。(根据您当前的配置,您可以执行user.receiver.all()
来获取接收到的消息,但这对于阅读器来说意义不大。)
你需要像
sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="messages_sent")
receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="messages_received")
之后可以使用user.messages_received.all()
和user.messages_sent.all()
。