[Django]-How to use django orm to get all the recipients to a message?

3👍

Use Q objects so that you can select both contacts messaged as part of a group and contacts that were individual recipients in the same queryset.

Then use distinct() so that you don’t get duplicates.

If you’re not familiar with the double underscore notation (e.g. groups__messages), then see the docs on following relationships “backward”.

Putting it all together, you have:

message = message.objects.get(id=message_id)
Contact.objects.filter(Q(groups__messages=message)|Q(messages=message)).distinct()

You may want to encapsulate the above query in a method on the Message model:

class Message(models.Model):
    # field definitions

    def get_recipients(self):
        return Contact.objects.filter(Q(groups__messages=message)|Q(messages=message)).distinct()

Then in your view, you can simply write message.get_recipients().

Leave a comment