我已經提出了與此問題相關的上一篇文章here,但因爲這是一個相關的,但新的問題我認爲最好是爲它製作另一篇文章。Django ORM - 左加入與WHERE子句
我使用Django 1.8
我有一個用戶模型和UserAction模型。用戶有一個類型。 UserAction有一段時間,表示動作持續了多長時間,還有一個start_time指示動作何時開始。他們是這樣的:
class User(models.Model):
user_type = models.IntegerField()
class UserAction:
user = models.ForeignKey(User)
time = models.IntegerField()
start_time = models.DateTimeField()
現在我想要做的就是給定類型和他們的行動,可選擇由START_TIME過濾的時間的總和的所有用戶。
什麼我做的是這樣的:
# stubbing in a start time to filter by
start_time = datetime.now() - datetime.timedelta(days=2)
# stubbing in a type
type = 2
# this gives me the users and the sum of the time of their actions, or 0 if no
# actions exist
q = User.objects.filter(user_type=type).values('id').annotate(total_time=Coalesce(Sum(useraction__time), 0)
# now I try to add the filter for start_time of the actions to be greater than or # equal to start_time
q = q.filter(useraction__start_time__gte=start_time)
現在是什麼這樣做當然是內連接上UserAction的,從而消除所有的用戶,無需操作。我真正想要做的就是將我的LEFT JOIN與WHERE子句相提並論,但對於我來說,我無法找到如何去做。我查看了文檔,查看了源代碼,但沒有找到答案。我(很漂亮)確定這是可以完成的事情,我只是沒有看到如何。任何人都可以將我指向正確的方向嗎?任何幫助將非常感激。非常感謝!
沒有用途的用戶應該包含在結果中嗎? – f43d65
@ f43d65 - 是的,他們應該 – TheMethod