django通过cocece从同一模型中获取最大长度值
我正在尝试使用ORM编写以下原始查询。我不确定是否可能。
select first_name,
middle_name,
COALESCE(middle_name, (
select middle_name
from contacts c2
where c2.first_name = c1.first_name
and c2.last_name = c1.last_name
and c2.middle_name is not null
order by length(c2.middle_name) desc
limit 1
)
) expected,
last_name
from contacts c1
预期的结果就像以下内容一样,如果middle_name为null,请从具有相同first_name和last_name的另一个记录中获取中间名。
id| first_name | middle_name | expected | last_name
1 | ahmet | <NULL> | burak | ozyurt
2 | ahmet | burak | burak | ozyurt
class Contact(models.Model):
first_name = models.CharField(max_length=250)
last_name = models.CharField(max_length=250, null=True, blank=True)
middle_name = models.CharField(max_length=250, null=True, blank=True)
DB:Postgres
Django版本:3.12
I'm trying to write the following raw query with the ORM. I'm not sure is it possible or not.
select first_name,
middle_name,
COALESCE(middle_name, (
select middle_name
from contacts c2
where c2.first_name = c1.first_name
and c2.last_name = c1.last_name
and c2.middle_name is not null
order by length(c2.middle_name) desc
limit 1
)
) expected,
last_name
from contacts c1
The expected result is like the following, if middle_name is null, get the middle name from another record that has the same first_name and last_name.
id| first_name | middle_name | expected | last_name
1 | ahmet | <NULL> | burak | ozyurt
2 | ahmet | burak | burak | ozyurt
class Contact(models.Model):
first_name = models.CharField(max_length=250)
last_name = models.CharField(max_length=250, null=True, blank=True)
middle_name = models.CharField(max_length=250, null=True, blank=True)
DB: Postgres
Django Version: 3.12
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过使用django orm,您可以使用以下代码
说明
models.OuterRef
用于从子查询的父级查询中引用该字段。-
order_by中的前缀(“ - Midder_name_len”)
用于降序顺序.values(“ Midder_name”)
用于仅选择midder_name
值。[:1]
是为了将子查询的结果限制为一个。提示
result.query
检查ORM将为您生成的查询。By using the django ORM, you can perform the same query by using the following code
Explanations
models.OuterRef
is used for referring to the field from the parent query of a subquery.-
prefix in theorder_by("-middle_name_len")
is for descending order.values("middle_name")
is for selecting onlymiddle_name
values.[:1]
is for limiting the result from the subquery to be one.Tips
result.query
to inspect what query the ORM will generate for you.