A
A
Andrei1penguin12022-04-05 17:11:09
Django
Andrei1penguin1, 2022-04-05 17:11:09

How to filter ForeignKey Django?

In chat, I need to get the number of unread messages for the user and I can't seem to get it done with django orm, here's a sketch:

chat.message_set.exclude(readers__contains=user).count()

But it fails with the corresponding error:
django.core.exceptions.FieldError: Related Field got invalid lookup:
contains
sum([1 for m in self.message_set.all() if user in m.readers.all()])

Can you please tell me how to solve this problem more efficiently?
Update:
I came up with a poor solution for me, but working and generally fast:
In the message model, all readers are stored in the ManyToManyField connection, which causes an error, or you can put all reader logins in one line and apply __contains to it already

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2022-04-05
@bacon

duy read the docs https://docs.djangoproject.com/en/4.0/topics/db/qu...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question