Django 在多对一反向关系中使用 QuerySet 获取特定对象
Django getting especific object using QuerySet in reverse relationship many-to-one
假设我有以下型号:
Chat(models.Model):
community = models.ForeignKey(Community, related_name="chats", null=True, blank=True)
....
Community(models.Model):
slug = models.CharField(max_length=250, unique=True, default='')
....
Profile(models.Model):
public_name = models.CharField(max_length=20, unique=True)
community_subscriptions = models.ManyToManyField('Community', through='CommunitySubscription')
chat_subscriptions = models.ManyToManyField('Chat', through='ChatSubscription')
....
ChatSubscription(models.Model):
profile = models.ForeignKey(Profile, unique=False, related_name='chat_subscription')
chat = models.ForeignKey(Chat, null=True, blank=True, related_name='chat_subscribers')
....
CommunitySubscription(models.Model):
....
在视图中,我想执行以下操作:
profileA = Profile.objects.get(public_name=public_nameA)
profileB = Profile.objects.get(public_name=public_nameB)
community = Community.objects.get(slug=community_slug)
try:
# I want to get the unique chat that involves both profiles for a specific community or get DoesNotExist (or None) if there is not such chat.
chat = Chat.objects.????????????
except Chat.DoesNotExist:
....
如果聊天存在,那么两个配置文件都会有一个 ChatSubscription 对象,将配置文件与聊天相关联。
是否可以在一行中使用 Django QuerySets 进行这种过滤?如果不是,在多行中执行此操作的最有效方法是什么?
非常感谢。
相当复杂,所以请尝试使用 Q object 执行 'AND' 查询(假设我知道您要执行的操作):
from django.db.models import Q
Chat.objects.filter(Q(chatsubscription__profile__in=[profileA,profileB]) & Q(community=communty))
假设我有以下型号:
Chat(models.Model):
community = models.ForeignKey(Community, related_name="chats", null=True, blank=True)
....
Community(models.Model):
slug = models.CharField(max_length=250, unique=True, default='')
....
Profile(models.Model):
public_name = models.CharField(max_length=20, unique=True)
community_subscriptions = models.ManyToManyField('Community', through='CommunitySubscription')
chat_subscriptions = models.ManyToManyField('Chat', through='ChatSubscription')
....
ChatSubscription(models.Model):
profile = models.ForeignKey(Profile, unique=False, related_name='chat_subscription')
chat = models.ForeignKey(Chat, null=True, blank=True, related_name='chat_subscribers')
....
CommunitySubscription(models.Model):
....
在视图中,我想执行以下操作:
profileA = Profile.objects.get(public_name=public_nameA)
profileB = Profile.objects.get(public_name=public_nameB)
community = Community.objects.get(slug=community_slug)
try:
# I want to get the unique chat that involves both profiles for a specific community or get DoesNotExist (or None) if there is not such chat.
chat = Chat.objects.????????????
except Chat.DoesNotExist:
....
如果聊天存在,那么两个配置文件都会有一个 ChatSubscription 对象,将配置文件与聊天相关联。
是否可以在一行中使用 Django QuerySets 进行这种过滤?如果不是,在多行中执行此操作的最有效方法是什么?
非常感谢。
相当复杂,所以请尝试使用 Q object 执行 'AND' 查询(假设我知道您要执行的操作):
from django.db.models import Q
Chat.objects.filter(Q(chatsubscription__profile__in=[profileA,profileB]) & Q(community=communty))