[Answered ]-Django ORM: Excluding Specific Record in Many-to-Many Relationship

1👍

Yes, this is the right way, you can filter with:

conversations = Conversation.objects.filter(members=profile_pk)  # or
conversations = Conversation.objects.filter(members=profile_object)  # or
conversations = Conversation.objects.filter(members__id=profile_pk)

Also, I want to exclude that member’s data from the result because I already have it.

The query will not fetch member data, it will only fech Conversations. If you then query myconversation.members.all(), you get all member data, including the one of the Profile.

If you want to exclude that Profile from the members when you fetch this, you can work with a Prefetch object:

from django.db.models import Prefetch

conversations = Conversation.objects.prefetch_related(
    Prefetch('members', Profile.objects.exclude(pk=profile_pk))
).filter(members=profile_pk)

The Conversations will then not contain the item with profile_pk as item of the Members.

Leave a comment