【发布时间】:2015-07-16 12:21:04
【问题描述】:
假设我有以下模型:
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 进行这种过滤?如果不是,在多行中最有效的方法是什么?
非常感谢。
【问题讨论】:
-
您想在社区中进行聊天,同时拥有这两个配置文件?我不完全了解配置文件的来源。
-
我想进行一个聊天,其中包含这两个特定的订阅者(个人资料的来源)并且属于一个特定的社区。span>
标签: python django django-queryset django-orm many-to-one