简体   繁体   English

带主键的原始查询

[英]raw query with primary key

My model 我的模特

class Despacho (models.Model):  
    bus=models.ForeignKey(Bus)  
    contador = models.IntegerField()
    cerrado = models.BooleanField(editable=False)

class Bus(models.Model):    
    numero_bus=models.CharField(max_length=255,unique=True)
    en_ruta = models.BooleanField(editable=False)   

I need a query to extract the data which I save a bus, and I enter a number of the bus and I need to know if there is a dispatch that matches the search try to do the following query 我需要一个查询来提取我保存总线的数据,然后输入一些总线,我需要知道是否有与搜索匹配的调度尝试执行以下查询

my database is postgresql 我的数据库是postgresql

d = Despacho.objects.raw('''SELECT * FROM operaciones_despacho WHERE operaciones_despacho.bus =  '%s' AND operaciones_despacho.cerrado = '%s'                                                    
;'''%(bus.numero_bus,False)) 

error : column operaciones_despacho.bus does not exist 错误:列operaciones_despacho.bus不存在

First up in Django, we use raw sql only in the rare instances when it's particularly hard to write an ORM query. 首先在Django中,我们仅在极少数情况下使用原始sql,因为编写ORM查询特别困难。 In this instance, writing an ORM query is much easier and shorter than a raw query. 在这种情况下,编写ORM查询比原始查询更容易和更短。

Despacho.objects.filter(bus=bus).filter(cerrado=False)

On those rare instances when you need to do a raw query, take care you use the params argument to raw instead of string formatting. 在您需要执行原始查询的极少数情况下,请注意使用params参数raw而不是字符串格式。 The correct way to write your raw query is 编写原始查询的正确方法是

Despacho.objects.raw('''SELECT * FROM operaciones_despacho WHERE operaciones_despacho.bus =  '%s' AND operaciones_despacho.cerrado = '%s'''' ,
 [bus.numero_bus,False]) 

But I emphasis once again that you should not be using a raw query here because it's a simple ORM query. 但我再次强调你不应该在这里使用原始查询,因为它是一个简单的ORM查询。

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

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