Camelot的文档说它使用Elixir模型。由于我有一段时间,我已经用它代替了另一个应用程序的灵丹妙药。现在我想直接在Camelot中使用SQLAlchemy/声明性模型。
StAccess上有一个post,称Camelot不依赖于灵丹妙药,使用不同的模型是可能的,但并没有说明如何使用。
Camelot的原始model.py
仅包含以下内容:
import camelot.types
from camelot.model import metadata, Entity, Field, ManyToOne, OneToMany, Unicode, Date, Integer, using_options
from camelot.view.elixir_admin import EntityAdmin
from camelot.view.forms import *
__metadata__ = metadata
我添加了SQLAlchemy模型,并将
model.py
更改为:import camelot.types
from camelot.model import metadata, Entity, Field, ManyToOne, OneToMany, Unicode, Date, using_options
from camelot.view.elixir_admin import EntityAdmin
from camelot.view.forms import *
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
__metadata__ = metadata
Base = declarative_base()
class Test(Base):
__tablename__ = "test"
id = Column(Integer, primary_key=True)
text = Column(String)
它不起作用。当我启动
main.py
时,我可以在侧栏中看到GUI和Test
,但看不到任何行。这是回溯的尾声:File "/usr/lib/python2.6/dist-packages/camelot/view/elixir_admin.py", line 52, in get_query
return self.entity.query
AttributeError: type object 'Test' has no attribute 'query'
这是第46-52行的
elixir_admin.py
代码:@model_function
def get_query(self):
""":return: an sqlalchemy query for all the objects that should be
displayed in the table or the selection view. Overwrite this method to
change the default query, which selects all rows in the database.
"""
return self.entity.query
如果这段代码导致了问题,我如何覆盖该方法来更改默认查询以使其工作?
如何在Camelot中使用SQLAlchemy/声明性模型?
最佳答案
下面是一些使用声明式为Camelot定义电影模型的示例代码,可以找到一些解释here。
import sqlalchemy.types
from sqlalchemy import Column
from sqlalchemy.ext.declarative import ( declarative_base,
_declarative_constructor )
from camelot.admin.entity_admin import EntityAdmin
from camelot.model import metadata
import camelot.types
from elixir import session
class Entity( object ):
def __init__( self, **kwargs ):
_declarative_constructor( self, **kwargs )
session.add( self )
Entity = declarative_base( cls = Entity,
metadata = metadata,
constructor = None )
class Movie( Entity ):
__tablename__ = 'movie'
id = Column( sqlalchemy.types.Integer, primary_key = True )
name = Column( sqlalchemy.types.Unicode(50), nullable = False )
cover = Column( camelot.types.Image(), nullable = True )
class Admin( EntityAdmin ):
list_display = ['name']
form_display = ['name', 'cover']