如何在related_name字段上进行查询?

时间:2013-11-27 14:46:30

标签: django django-models django-orm

我必须通过ForeignKey

连接模型
class User(AbstractUser):
   ...

class PrivateMessage(models.Model):
    user_from = models.ForeignKey(
        User,
        verbose_name=u'From',
        related_name='sent_messages',
    )
    user_to = models.ForeignKey(
        User,
        verbose_name=u'To',
        related_name='received_messages',
    )

有没有办法获取特定用户的所有地址。例如,如果

u = User.objects.get(id=1)
messages = PrivateMessage.objects.filter(user_from=u)
for m in messages:
    users.add(m.user_to)

如何仅使用Django ORM方法获取这些消息中出现在user_to中的用户列表?

3 个答案:

答案 0 :(得分:1)

我认为更好的想法是在ManyToManyField模型上定义User

class User(AbstractUser):
    #...
    receivers = models.ManyToManyField('self', through='Message',
                                      symmetrical=False, related_name="senders")

class Message(models.Model):
    user_from = models.ForeignKey(MyUser, related_name='messages_from')
    user_to = models.ForeignKey(MyUser, related_name='messages_to')
    message = models.CharField(max_length=100, default="")
    #...

然后在另一端检索用户列表,您只需执行以下操作:

User.objects.get(id=1).receivers.all()  # who I sent the message to
User.objects.get(id=1).senders.all()    # who sent me a message

这样你就有了一个很好的清晰API。

答案 1 :(得分:1)

最后,我最后写了三个问题:

    users_from = set(PrivateMessage.objects.filter(
        user_to=self.request.user,
    ).values_list(
        'user_from__pk',
        flat=True,
    ))
    users_to = set(PrivateMessage.objects.filter(
        user_from=self.request.user,
    ).values_list(
        'user_to__pk',
        flat=True,
    ))
    interlocutors = User.objects.filter(pk__in=users_from.union(users_to))

答案 2 :(得分:0)

我看到了docs

也许你可以试试:

u = User.objects.get(id=1)
users = User.objects.filter(received_messages__user_from=u).distinct()