Python Camelot是否绑定到Elixir?
作者:互联网
Camelot的文档说它使用Elixir模型.由于SQLAlchemy在一段时间内包含了declarative_base,因此我在另一个应用程序中使用了它而不是Elixir.现在,我想直接在Camelot中使用SQLAlchemy /声明性模型.
Stackoverflow上有一个post,它表示Camelot与Elixir无关,并且可以使用不同的模型,但未说明如何使用.
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 /声明性模型?
解决方法:
这是一些使用Declarative为Camelot定义Movie模型的示例代码,可以找到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']
标签:sqlalchemy,crud,python-elixir,python 来源: https://codeday.me/bug/20191201/2082172.html