如果发生对话,则过滤掉用户

时间:2017-08-31 09:49:10

标签: python django

这是我的模特

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()

如果我们在社交网络上看到,当前用户向他们发送了消息或者他们向当前用户发送了消息时,如何过滤掉用户?

2 个答案:

答案 0 :(得分:2)

您可以将filter()Q对象结合使用,这样您就可以进行更复杂的查询(在您的情况下, OR 表达式):

>>> from django.db.models import Q
>>> user = request.user  # Take the current user
>>> Message.objects.filter(Q(sender=user) | Q(receiver=user))  # Filter messages where the sender or the receiver is the current user
<QuerySet [...]>

答案 1 :(得分:0)

尝试这样的事情: 1. user_obj = User.objects.filter(sender__receiver__pk = request.user.id) 2. users = User.objects.filter(sender__receiver = request.user)