我有类似 django 的模型:
class User(models.Model):
name = models.CharField(max_length = 128)
class Message(models.Model):
sender = models.ForeignKey(User, related_name = 'messages_sent')
recipient = models.ForeignKey(User, related_name = 'messages_recieved')
subject = models.CharField(max_length = 128)
body = models.CharField(max_length = 3500)
class Response(models.Model):
message = models.OneToOneField(Message, primary_key = True)
reply = models.TextField()
我正在尝试为没有响应的用户获取所有消息,我会在 SQL 中这样写:
select * from user u
join message m on (u.id = m.recipient_id)
left join response r on (m.id = r.message_id)
where r.message_id = null
我认为这样做的自然方法是:
u.messages_recieved.filter(response = None)
或者
u.messages_recieved.filter(response__message_id__isnull = True)
但生成的 SQL 总是最终是:
WHERE ("project_message"."recipient_id" = 1 AND "project_message"."id" IS NULL)
我是在做一些愚蠢的事情,还是这是 Django 中的一个错误?