Answer the question
In order to leave comments, you need to log in
How to annotate the number of M2M objects of a ManyToOneRelation field in a queryset?
I'm trying to sort a list of ticket objects that have chats inside by the number of unread messages in those chats. Reading the documentation on Django aggregation, I got completely confused.
There are models:
class Ticket(models.Model):
name = models.CharField(max_length=100)
user = models.ForignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="tickets")
class Chat(models.Model):
name = models.CharField(max_length=100)
participants = models.ManyToManyField(AUTH_USER_MODEL, related_name="chats")
ticket = models.ForignKey("tickets.Ticket", on_delete=models.CASCADE)
class Message(models.Model):
user = models.ForignKey(AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
chat = models.ForignKey("tickets.Chat", on_delete=models.CASCADE)
text = models.TextField()
read = models.BooleanField(default=False)
participants
this user exists in descending order. Answer the question
In order to leave comments, you need to log in
The data model is incorrect. The message should become read for a specific chat participant, and for you - for everyone at once. And it's better to track the date of the first unread + the number in the "participant" model - then everything is much simpler.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question