creating django model for existing database/sql view?

℡╲_俬逩灬. 提交于 2019-12-20 15:22:37

问题


I have inserted a definition for a view in $template_dir/sql/$someTableName.sql file. (create or replace view) so every time I run syncdb, the db views are created.

Can I create in models.py a python class which accesses that view?

Is it better practice to just use python's raw sql functionality instead?

---EDIT---

Another problem I have is that the view doesn't have a primary key, but django seems to be assuming there will be one because I get an error caught an exception while rendering: (1054, "Unknown column 'appName_currentleagues.id' in 'field list'") But I don't have such a member defined:

Class CurrentLeagues(models.Model):
        League = models.ForeignKey(League)
        class Meta:
                managed = False

So my guess is that django reasonably sees that I don't define a primary key in the CurrentLeagues class, so Django assumes there's one called id. Is there a way to tell Django that there is no primary key (since this is actually a view), or is that not even my problem?


回答1:


See Unmanaged models

You define the model as usual and add managed = False to the meta options:

class MyModel(models.Model):
    ...
    class Meta:
         managed = False



回答2:


Try to use python manage.py inspectdb or python manage.py inspectdb > models.py



来源:https://stackoverflow.com/questions/2245956/creating-django-model-for-existing-database-sql-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!