簡體   English   中英

Django ORM:排除多對多關系中的特定記錄

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

我在兩個模型 Profile 和 Conversation 之間有一個多對多的關系,如下所示:

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

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

現在我想 select 特定個人資料是其中成員的所有對話,我嘗試了這個,但我不確定它是否是正確的方法:

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

另外,我想從結果中排除該成員的數據,因為我已經有了它,還是應該在客戶端排除他的數據?

的,這是正確的方法,你可以過濾:

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

另外,我想從結果中排除該成員的數據,因為我已經有了它。

該查詢不會獲取成員數據,它只會獲取Conversation 如果您隨后查詢myconversation.members.all() ,您將獲得所有成員數據,包括Profile之一。

如果您想在獲取此配置文件時從成員中排除該Profile ,您可以使用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)

然后, Conversation將不包含具有profile_pk作為Member項目的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM