Home > front end >  Django ORM: Excluding Specific Record in Many-to-Many Relationship
Django ORM: Excluding Specific Record in Many-to-Many Relationship

Time:01-03

I have a many-to-many relationship between two models Profile and Conversation like this:

class Profile(models.Model):
    # ...

class Conversation(models.Model):
    members = models.ManyToManyField(Profile, related_name="conversations")

Now I want to select all the conversations that a specific profile is a member in it, I tried this which worked but I'm not sure if it's the right way:

conversations = Conversation.objects.filter(members='<profile_pk>')

Also, I want to exclude that member's data from the result because I already have it, or should I exclude his data on the client side?

CodePudding user response:

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.

  • Related