gpt4 book ai didi

sql - 如何在django中使用sql语句?

转载 作者:行者123 更新时间:2023-12-02 00:57:32 25 4
gpt4 key购买 nike

我想从我的数据库中获取最新日期。这是我的 sql 语句。

select "RegDate"
from "Dev"
where "RegDate" = (
select max("RegDate") from "Dev")

它在我的数据库中有效。但是我如何在 Django 中使用它呢?

我尝试了这些代码,但它返回错误。这些代码在 views.py 中。

版本 1:

lastest_date = Dev.objects.filter(reg_date=max(reg_date)) 

错误:

'NoneType' object is not iterable

版本 2:

last_activation_date = Dev.objects.filter(regdate='reg_date').order_by('-regdate')[0]

错误:

"'reg_date' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."

我在类(class)开始时定义了 reg_date。

我应该为此做什么?

最佳答案

你把事情搞得太复杂了,你只需按 regdate 订购即可,就是这样:

last_activation_<b>dev</b> = Dev.objects<b>.order_by('-regdate').first()</b>

.first()将返回这样的 Dev对象(如果可用)或 None如果没有Dev对象。

如果您只对 regdate 感兴趣列本身,您可以使用 .values_list(..) :

last_activation_date = Dev.objects.order_by('-regdate')<b>.values_list('regdate', flat=True)</b>.first()

通过使用 .filter()你实际上是在过滤 Dev表格 Dev记录 regdate列的 'reg_date' , 自 'reg_date'不是有效的日期时间格式,因此会产生错误。

关于sql - 如何在django中使用sql语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53205537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com