Mik*_*ike 5 python django many-to-many django-queryset
我有两个类用于我正在处理的消息传递模块.这个想法是一个参与者由一组参与者(两个或更多)代表.我正在努力寻找一种通过逻辑来查找对话的方法,说明我想要找到的所需对话有以下参与者.Conversation.objects.filter(participants__in=[p1, p2])
然而,我试过这样做是OR样式查询,p1是参与者,p2是参与者.我想要p1和p2和... pN是参与者.有帮助吗?
class Conversation(models.Model):
date_started = models.DateTimeField(auto_now_add=True)
participants = models.ManyToManyField(User)
def get_messages(self):
return Message.objects.filter(conversation=self)
def new_message(self, sender, body):
Message.objects.create(sender=sender, body=body, conversation=self)
self.save()
class Message(models.Model):
sender = models.ForeignKey(User)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
conversation = models.ForeignKey(Conversation)
def __unicodde__(self):
return body + "-" + sender
Run Code Online (Sandbox Code Playgroud)
我认为你只需要迭代过滤。这可能完全是无稽之谈,因为我有点睡眠不足,但也许是这样的管理方法:
class ConversationManager(models.Manager):
def has_all(self, participants):
# Start with all conversations
reducedQs = self.get_query_set()
for p in participants:
# Reduce to conversations that have a participant "p"
reducedQs = reducedQs.filter(participants__id=p.id)
return reducedQs
Run Code Online (Sandbox Code Playgroud)
一般来说,您应该养成使用表级查询管理器方法而不是类方法的习惯。通过这种方式,您将得到一个查询集,您可以根据需要进一步过滤。
受到文档中具有成员名称 Paul 的所有组的查询和此答案的启发。