django orm错误:FieldDoesNotExist: Raw query must include the primary key
http://www.chenxm.cc/article/1141.html背景:python3.7django 3.1使用django中model.object.raw(sql)触发错误提示:django.core.exceptions.FieldDoesNotExist: Raw query must include the primary keysql语句:SELECT ROUND(avg(flow),2) as flow FROM "detetor_index" WHEREdetetor_key in {key_li} and flow >0and 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.modelfields = [self.model_fields.get(c) for c in self.columns]因此解决方法比较简单,只需要添加索引主键SELECT id,ROUND(avg(flow),2) as flow FROM "detetor_index" WHEREdetetor_key in {key_li} and flow >0and ctime BETWEEN '{start_time}' and '{end_time}'本文地址: http://www.chenxm.cc/article/1141.html版权声明: 本文为原创文章,版权归 陈新明 所有,欢迎分享本文,转载请保留出处!