Jup
Jup

Reputation: 21

Why Django ask for the id in raw queries?

I'm doing a raw query in Django 3.10.5
###################################
MediosBasicos.objects.raw('SELECT descripcion, COUNT("descripcion") AS "descrip" FROM "basedatos_mediosbasicos" GROUP BY "descripcion"')
###################################
But for some reazon it ask me for the id. That has no sence. Someone knows why this happends or what is the purpose of it?

Upvotes: 0

Views: 299

Answers (1)

DeaX StormZ
DeaX StormZ

Reputation: 86

First of all you should avoid doing raw queries unless there is nothing in the Django ORM that fits your needs (I doubt it is the case, so you should check Django ORM doc).

If you still have to do a raw query, you must include the id in your query, as Django documentation states :

There is only one field that you can’t leave out - the primary key field. Django uses the primary key to identify model instances, so it must always be included in a raw query. A FieldDoesNotExist exception will be raised if you forget to include the primary key.

https://docs.djangoproject.com/en/4.1/topics/db/sql/#deferring-model-fields

Upvotes: 1

Related Questions