FieldDoesNotExist: Raw query must include the primary key

created at 07-16-2021 views: 1

environment

  • python3.7
  • django 3.1

Use model.object.raw(sql) in django  triggered an error message:

django.core.exceptions.FieldDoesNotExist: Raw query must include the primary key

sql statement:

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}'

Solution

After reading the source code, it is found that the primary key field must be included in the sql statement because of the django orm query.

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]

Therefore, the solution is relatively simple, only need to add the index primary key

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}'
Please log in to leave a comment.