简体   繁体   English

Django:原始查询从表中获取值

[英]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. 在pgAdminIII中执行此查询时,它会根据查询从两个表中返回结果,但是当我在django视图中使用相同的结果时,它将仅从第一个表中获取结果,而忽略了v.ip,v.id和v.name字段值。

Any suggestions? 有什么建议么?

When you use raw queries, Django, will add the extra fields automagically to instances of your model (in this case Job). 当您使用原始查询时,Django会自动将额外的字段添加到模型实例(在本例中为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. 为了避免这种情况,您应该显式命名查询中涉及的secondy表中的所有列。 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 . 现在,您将在每个作业实例中都有一个名为vidvname You do not need to have a model created for the virtualmachine table. 您无需为virtualmachine表创建模型。

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 综上所述,上面的查询很容易使用ORM编写,因此您可能应该避免在此处进行原始查询

the jobs manager only returns fields from its mapped table. jobs管理器仅返回其映射表中的字段。 You need to create a model for the clientadmin_virtualmachine table as well and use it in a ForeignKey 您还需要为clientadmin_virtualmachine表创建一个模型,并在ForeignKey使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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