简体   繁体   中英

Django : Raw query fetching values from table

job = jobs.objects.raw('select j.*, v.ip, v.id , v.name from jobs_jobs as j,clientadmin_virtualmachine as v where (j.ip_id)::int = v.id order by j.date desc')

While executing this query in pgAdminIII it returns result from both tables as per the query but when I use the same in django view it fetches result from first table only, ignoring the v.ip, v.id , v.name field values.

Any suggestions?

When you use raw queries, Django, will add the extra fields automagically to instances of your model (in this case Job). However there is always confusion when columns names overlap. Which column get's mapped to which field? To avoid this you should explicitly name all columns from the secondy tables involved in the query. Something like this:

select j.*, v.ip, v.id as vid , v.name as vname from jobs_jobs as
  j,clientadmin_virtualmachine as v where (j.ip_id)::int = v.id 
  order by j.date desc

Now you will have a field in each job instance named vid and vname . You do not need to have a model created for the virtualmachine table.

Having said all this, the above query is something that can be easily written using the ORM so you probably ought to avoid a raw query here

the jobs manager only returns fields from its mapped table. You need to create a model for the clientadmin_virtualmachine table as well and use it in a ForeignKey

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