可以在Django中使用数据库视图作为模型吗? [英] Can I use a database view as a model in Django?

查看:752
本文介绍了可以在Django中使用数据库视图作为模型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用我在数据库中创建的视图作为我的django视图的源。



这是可能的,没有使用自定义sql ?



****** 13/02/09更新***********



/ p>像许多答案中的建议一样,你可以在数据库中自己创建一个视图,然后通过在models.py中定义它来在API中使用它。



一些警告虽然:




  • manage.py syncdb不再工作

  • 视图需要与其他所有模型(表格)一样,例如,如果您的应用程序被称为事物,那么您的视图将需要被称为thing_ $ viewname


解决方案

自Django 1.1起,您可以使用 Options.managed



对于旧版本,您可以轻松地为视图定义一个Model类并使用它你的其他看法。我刚刚使用基于Sqlite的应用程序测试它,它似乎工作正常。如果您的视图的主键列未命名为id,并且如果视图未调用app_classname,则在Meta选项中指定视图的名称,请确保添加主键字段。



唯一的问题是,syncdb命令会引发异常,因为Django会尝试创建表。您可以通过在不同于models.py的独立Python文件中定义视图模型来防止这种情况。这样一来Django就会看到它们,当我们检查models.py来确定为应用程序创建的模型时,Django将不会尝试创建表。


i'd like to use a view i've created in my database as the source for my django-view.

Is this possible, without using custom sql?

******13/02/09 UPDATE***********

Like many of the answers suggest, you can just make your own view in the database and then use it within the API by defining it in models.py.

some warning though:

  • manage.py syncdb will not work anymore
  • the view need the same thing at the start of its name as all the other models(tables) e.g if your app is called "thing" then your view will need to be called thing_$viewname

解决方案

Since Django 1.1, you can use Options.managed for that.

For older versions, you can easily define a Model class for a view and use it like your other views. I just tested it using a Sqlite-based app and it seems to work fine. Just make sure to add a primary key field if your view's "primary key" column is not named 'id' and specify the view's name in the Meta options if your view is not called 'app_classname'.

The only problem is that the "syncdb" command will raise an exception since Django will try to create the table. You can prevent that by defining the 'view models' in a separate Python file, different than models.py. This way, Django will not see them when introspecting models.py to determine the models to create for the app and therefor will not attempt to create the table.

这篇关于可以在Django中使用数据库视图作为模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆