背景:
python3.7
django 3.1
使用django中model.object.raw(sql)触发错误提示:
django.core.exceptions.FieldDoesNotExist: Raw query must include the primary key
sql语句:
SELECT ROUND(avg(flow),2) as flow FROM "detetor_index" WHERE detetor_key in {key_li} and flow >0 and ctime BETWEEN '{start_time}' and '{end_time}'
解决方法:
经过阅读源码发现,是因为django orm查询,sql语句中必须要有主键这个字段。
model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order() if self.model._meta.pk.attname not in model_init_names: raise exceptions.FieldDoesNotExist( 'Raw query must include the primary key' ) model_cls = self.model fields = [self.model_fields.get(c) for c in self.columns]
因此解决方法比较简单,只需要添加索引主键
SELECT id,ROUND(avg(flow),2) as flow FROM "detetor_index" WHERE detetor_key in {key_li} and flow >0 and ctime BETWEEN '{start_time}' and '{end_time}'
还没有留言,还不快点抢沙发?