使用Django

时间:2017-10-26 18:05:23

标签: python sql-server django

我对Django很新。我试图使用Django App从SQL服务器查询数据。我能够连接默认的Django数据库并从那里获取数据,但是当我尝试查询现有数据库时,Django不断抛出错误。 (对于格式化中的缩进错误道歉,但在我的脚本中没有问题)

views.py显示以下错误:

from django.http import HttpResponse
from django.template import Context,Template,RequestContext
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from ForecastApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
#from django.db import connection
import os
import csv
import json
import subprocess
from subprocess import *
from operator import itemgetter
from datetime import datetime
import pyodbc
from logging import getLogger
from .models import Actuals
from .models import forecastfuture
ss = forecastfuture.objects.using('default').all()
    print len(ss)
    for row in ss:
        print (row.region) #works fine
tt = Actuals.objects.using('Forecasting').all()
    print len(tt)
        for row in tt:
            print (row.Region)

[Microsoft] [SQL Server Native Client 11.0] [SQL Server]无效的列名称“id”。 (207)

我已按照文档中的说明设置了routers.py和models.py以及settings.py。

routers.py

class App1Router(object): #pardon my poor indentations here while posting
def db_for_read(self, model, **hints):

    if model._meta.app_label == 'ForecastApp':
        return 'Forecasting'
    return 'default'

def db_for_write(self, model, **hints):

    if model._meta.app_label == 'ForecastApp':
        return 'Forecasting'
    return 'default'

def allow_relation(self, obj1, obj2, **hints):

    if obj1._meta.app_label == 'ForecastApp' and obj2._meta.app_label == 'ForecastApp':
        return True
    # Allow if neither is chinook app
    elif 'ForecastApp' not in [obj1._meta.app_label, obj2._meta.app_label]:
        return True
    return False

def allow_syncdb(self, db, model):
    if db == 'Forecasting' or model._meta.app_label == "ForecastApp":
        return False # we're not using syncdb on our legacy database
    else: # but all other models/databases are fine
        return True

models.py

class Actuals(models.Model):
    date = models.DateTimeField(db_column='Date', blank=True, null=True)
    values = models.FloatField(db_column='Values', blank=True, null=True)
    region = models.CharField(db_column='Region', max_length=50, blank=True, null=True)
    metric = models.CharField(db_column='Metric', max_length=50, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'actuals'

class migrations(models.Model):
    app =models.CharField(max_length=255)
    name =models.CharField(max_length=255)
    applied = models.DateTimeField()

class forecastfuture(models.Model):
    caseId = models.IntegerField(null=False)
    date = models.DateField(null=False)
    forecast=models.FloatField(null=False)
    metric = models.CharField(max_length=255,null=False)
    region = models.CharField(max_length=255,null=False)

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc', 
        'NAME': 'ForecastAppDjango',   
        'USER': '',                    
        'PASSWORD': '',                
        'HOST': 'abc.com\\sql',        
        'PORT': '1433',                
        'OPTIONS': {
                'host_is_server': True,
                'driver' : 'SQL Server Native Client 11.0',
                'trusted_connection':'yes',

        },
    },

    'Forecasting': {
        'ENGINE': 'sql_server.pyodbc', 
        'NAME': 'Forecasting',         
        'USER': '',                    
        'PASSWORD': '',                
        'HOST': 'abc.com\\sqlt',.
        'PORT': '1433',         
        'OPTIONS': {
                'host_is_server': True,
                'driver' : 'SQL Server Native Client 11.0',
                'trusted_connection':'yes',

        },
    }
}

DATABASE_ROUTERS = ['ForecastApp.routers.App1Router']

到目前为止,我已尝试:manage.py makemigrations并成功迁移命令。

Actuals表是:

| Date | Values | Region | Metric|
|2012-01-01 00:00:00.000 | 1000 | Region1 | Demand |

manage.py inspectdb --database“Forecasting”也没关系。

Q1:外部数据库预测没有主键。这是一个要求吗? Q2:我在views.py或models.py中做错了什么?

提前感谢您的建议。

1 个答案:

答案 0 :(得分:0)

Q2:我认为您的表forecastfuture和Actuals具有不同的结构ID列在表forecastfuture中是额外的