简体   繁体   English

如何在 Django ORM 中获取常量列?

[英]How do I get a constant column in a Django ORM?

I am studying ORM.我正在学习 ORM。 However, there are some things I don't understand even after reading the documentation.但是,即使在阅读文档后,我也有一些不明白的地方。

How do I get a constant column in a Django ORM?如何在 Django ORM 中获取常量列?

SQL is here. SQL 在这里。

select *, 'a' as a from book;

This is the query set I tried这是我试过的查询集

Book.objects.annotate(a=Value('a'))

The error is here.错误就在这里。

django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field

When executing your code, I get the following error:执行您的代码时,我收到以下错误:

FieldError('Cannot resolve expression type, unknown output_field')

Which means django doesn't know the type that your annotated field should result in.这意味着 django 不知道您的注释字段应该产生的类型。

To fix this, you need to wrap your annotation in an ExpressionWrapper :要解决此问题,您需要将注释包装在ExpressionWrapper

from django.db.models import Value, ExpressionWrapper

Book.objects.annotate(a=ExpressionWrapper(
    Value('a'), 
    output_field=models.CharField(max_length=45),
))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM