Reputation: 4170
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)
Upvotes: 4
Views: 18908
Reputation: 805
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
Upvotes: 3
Reputation: 4170
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)
Upvotes: 2