Django backward foreign key query not working


hi i am working on a chat application on django with django channels and i am trying to query all the first messages of the user here when i do


it is throwing

AttributeError at /
'User' object has no attribute 'message_set'

full traceback:

Traceback (most recent call last):
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/", line 47, in inner
    response = get_response(request)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/__neeraj__/Documents/chat/home/", line 10, in index
AttributeError: 'User' object has no attribute 'message_set'


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:
    return render(request, "index.html", context=context)

is this because i have double foreign key reference of user model on message table?


You have specified that related_name quite incorrectly.
(With your current configuration, you could do user.receiver.all() to get received messages, but that makes little sense for a reader.)

You’ll want something like

sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="messages_sent")
receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="messages_received")

after which you can use user.messages_received.all() and user.messages_sent.all().

Answered By – AKX

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published