【问题标题】:Django getting especific object using QuerySet in reverse relationship many-to-oneDjango 使用 QuerySet 以多对一的反向关系获取特定对象
【发布时间】: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


【解决方案1】:

相当复杂,因此请尝试使用Q object 进行“AND”查询(假设我得到了您想要做的事情):

from django.db.models import Q

Chat.objects.filter(Q(chatsubscription__profile__in=[profileA,profileB]) & Q(community=communty))    

【讨论】:

  • 看起来不错,是的,看来你明白我需要什么了!我唯一的疑问:Q(chatsubscription__profile__in=[profileA,profileB]) 会检查 profileA 和 profileB 是否是同一 Chat 对象的订阅者,还是会返回具有 profilerA 或 profileB 作为订阅者的 Chat 对象?
  • 很确定它会检查两者。因此,如果其中一个存在但不是两者都存在,它不会返回任何东西,我之前用我自己的模型尝试过这个。但是你总是可以在 shell 中测试它来确定!
猜你喜欢
  • 1970-01-01
  • 2011-06-16
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2022-01-17
  • 2016-09-15
相关资源
最近更新 更多