Django实现中的情况如下:
我想将这些模型加在一起以获取相关信息。实施例
class CurtainOrder(models.Model):
order = models.ForeignKey('curtainconfig.Order', related_name='curtains')
order_number = models.IntegerField(unique=True)
order_type = models.CharField(max_length=50)
class ProductionOrder(models.Model):
id = models.IntegerField(primary_key=True, db_column=u'lOrder_id')
order_number = models.IntegerField(db_column=u'nOrderNumber')
status = models.TextField(db_column=u'cExternalDescription')
class Meta:
app_label = u'backend'
db_table = u'ORDER'
database_name = 'production'
通过查询获得结果如下:
SELECT
co.order_number, co.order_type, po.status
FROM
CurtainOrder co
INNER JOIN
[production].dbo.ProductionOrder po on po.order_number = co.order_number
但是如何在Django代码中获得相同的结果?
我试图在Django https://docs.djangoproject.com/en/1.8/topics/db/sql/中使用SQL查询,如下所示:
from django.db import connections
cursor = connections['default'].cursor()
sql = """SELECT
co.order_number, co.order_type, po.status
FROM
CurtainOrder co
INNER JOIN
[production].dbo.ProductionOrder po on po.order_number = co.order_number """
cursor.execute(sql)
row = cursor.fetchone()
这是返回错误:return Database.Cursor.execute(self,query) OperationalError:接近“。”:语法错误
加入'production'数据库时会出错,但直接在数据库管理应用程序中执行SQL查询会很好。