[英]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.