Home > Mobile >  Django backward foreign key query not working
Django backward foreign key query not working

Time:09-27

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

user.message_set.all()

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/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'

my 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)

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

CodePudding user response:

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().

  • Related