简体   繁体   中英

Django - Raw query must include the primary key

There is a similar question here - Raw query must include the primary key

However I'm running off of a legacy DB and therefore can't figure out what the issue is with the Primary Key.

This is my RAW query -

trg = Trgjob.objects.db_manager('AdmiralDEV').raw("""
    SELECT jobdep_id, jm.jobmst_id, jobdep_type, (jm1.jobmst_prntname + '\' + jm1.jobmst_name) AS jobdep_jobmst,
    jobdep_operator, jobdep_status, jobdep_joblogic, jobdep_ingroup, jobdep_dateoffset, jobdep_instoffset,
    jobdep_canignore, jobdep_filename, jobdep_filetype, jobdep_fileextent, nodmst_id, varmst_id, jobdep_value
    FROM Jobdep jd
    INNER JOIN Jobmst jm ON jd.jobmst_id = jm.jobmst_id
    INNER JOIN Jobmst jm1 ON jd.jobdep_jobmst = jm1.jobmst_id
    WHERE jm.jobmst_id = 9878""")

On the DB works fine, but in django I get the following failure -

Raw query must include the primary key

The primary key on this model is "jobdep_id" as seen in the models.py here -

class Jobdep(models.Model):
    jobdep_id = models.IntegerField(primary_key=True)

Try to write query as:

"SELECT jobdep_id AS id ..."

maybe it helps.

The issue was indeed my models.py I had to update it as follows -

class Jobdep(models.Model):
    jobdep_id = models.IntegerField(db_column='jobdep_id', primary_key=True)

If you use Manager.raw() it's required to provide the id. ( https://docs.djangoproject.com/en/2.2/topics/db/sql/#performing-raw-sql-queries )

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. An InvalidQuery exception will be raised if you forget to include the primary key.

But you can execute custom SQL directly to avoid this. See more on Django documentation https://docs.djangoproject.com/en/2.2/topics/db/sql/#executing-custom-sql-directly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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