Django:过滤不同的数据

时间:2017-11-13 07:13:16

标签: python django

我正在尝试构建一个消息传递应用。这是我的模特,

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

这是我在视野中尝试的,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')

在我的模板中,

{% for abc in data %}
    {{ abc.receiver }}<br />
{% endfor %}

如何打印出不同的用户?

2 个答案:

答案 0 :(得分:0)

您可以单独查询发件人和收件人,然后使用set()获取不同的值

users = set([x.receiver for x in Message.objects.filter(sender = request.user)] + [x.sender for x in Message.objects.filter(receiver = request.user)]) 

答案 1 :(得分:0)

使用您的数据库结构,我只能通过这样的数据库查询接收您想要的内容(不确定它是否可以在django orm中重现):

SELECT u.*, m.*
FROM auth_user u
  INNER JOIN (
     SELECT
       user_id,
       MAX(message_id) AS message_id
     FROM
       (
         SELECT
           m2.receiver_id AS user_id,
           MAX(id)        AS message_id
         FROM yourapp_message m2
         GROUP BY m2.receiver_id
         UNION
         SELECT
           m2.sender_id AS user_id,
           MAX(id)      AS message_id
         FROM yourapp_message m2
         GROUP BY m2.sender_id
       ) t
     GROUP BY user_id) t2 ON u.id = t2.user_id
  INNER JOIN yourapp_message m ON m.id = t2.message_id
ORDER BY m.id DESC