[英]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:我在两个模型 Profile 和 Conversation 之间有一个多对多的关系,如下所示:
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:现在我想 select 特定个人资料是其中成员的所有对话,我尝试了这个,但我不确定它是否是正确的方法:
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.该查询不会获取成员数据,它只会获取
Conversation
。 If you then query myconversation.members.all()
, you get all member data, including the one of the Profile
.如果您随后查询
myconversation.members.all()
,您将获得所有成员数据,包括Profile
之一。
If you want to exclude that Profile
from the members when you fetch this, you can work with a Prefetch
object:如果您想在获取此配置文件时从成员中排除该
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)
The Conversation
s will then not contain the item with profile_pk
as item of the Member
s.然后,
Conversation
将不包含具有profile_pk
作为Member
项目的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.