简体   繁体   中英

Django ORM: Excluding Specific Record in Many-to-Many Relationship

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?

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 Conversation s. 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 Conversation s will then not contain the item with profile_pk as item of the Member s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM