title: Querying / Retrieving Data from SQL Server using Django
body: <p>I am pretty new to Django. I am trying to query data from SQL server using a Django App. I am able to connect with the default Django database and fetch data from there but Django keeps throwing an error when I try to query an existing database. (Apologies for indentation mistakes in formatting here but it is ok in my scripts) </p>
  
  <p>views.py shows the following error:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>[Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'id'. (207)  </p>
  
  <p>I have set up routers.py and models.py and settings.py per instructions in documentation.</p>
  
  <p>routers.py</p>
  
  <pre><code>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
  </code></pre>
  
  <p>models.py</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>settings.py</p>
  
  <pre><code>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']
  </code></pre>
  
  <p>So far I ve tried to: manage.py makemigrations and migrate commands successfully.</p>
  
  <p>Actuals table is:</p>
  
  <pre><code>| Date | Values | Region | Metric|
  |2012-01-01 00:00:00.000 | 1000 | Region1 | Demand |
  </code></pre>
  
  <p>manage.py inspectdb --database "Forecasting" was also ok.</p>
  
  <p>Q1: External DB forecasting does not have a primary key. Is this a requirement?
  Q2: What am I doing wrong in my views.py or models.py ?</p>
  
  <p>Thank you for your suggestions in advance.</p>