我正在尝试使用 Django(django 1.11.4)从 SQL-Server 视图(sql server 2012 - 我为此使用 sql_server.pyodbc [aka django-pyodbc])读取数据,但似乎没有任何效果。
这是我的模型:
class NumUsersAddedPerWeek(models.Model):
id = models.BigIntegerField(primary_key=True)
year = models.IntegerField('Year')
week = models.IntegerField('Week')
num_added = models.IntegerField('Number of Users Added')
if not settings.RUNNING_UNITTESTS:
class Meta:
managed = False
db_table = 'num_users_added_per_week'
以下是创建数据库视图的方式:
create view num_users_added_per_week
as
select row_number() over(order by datepart(year, created_at), datepart(week, created_at)) as 'id',
datepart(year, created_at) as 'year', datepart(week, created_at) as 'week', count(*) as 'num_added'
from [<database name>].[dbo].[<table name>]
where status = 'active' and created_at is not null
group by datepart(year, created_at), datepart(week, created_at)
该视图本身就可以正常工作(例如,运行'select * from num_users_added_per_week'运行得很好(并且非常快)......
我使用以下 django 命令(即“action”)尝试了 3 种不同的方式来尝试通过模型提取数据,但都没有奏效(尽管从其他帖子来看,这些方法似乎适用于以前版本的 django ) :(:
from django.core.management.base import BaseCommand, CommandError
from <project name>.models import NumUsersAddedPerWeek
from django.db import connection
class Command(BaseCommand):
def handle(self, *args, **options):
# attempt # 1 ...
num_users_info = NumUsersAddedPerWeek.objects.all()
info = num_users_info.first()
for info in num_users_info:
print(info)
# attempt # 2 ...
cursor = connection.cursor()
cursor.execute('select * from num_users_added_per_week')
result = cursor.fetchall()
# attempt # 3 ...
num_users_info = NumUsersAddedPerWeek.objects.raw('select * from num_users_added_per_week')
for info in num_users_info:
print(info)
3 种不同方法中的每一种都给了我相同的错误:“('42S02',“[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'num_users_added_per_week'。(208)(SQLExecDirectW)”) "
请注意:我的迁移运行良好 -class Meta: managed = False
在您不希望迁移创建/更新/删除您的 sql 表结构的情况下,添加对于最新版本的 Django 至关重要...