SQLAlchemy:我需要2个课吗?

时间:2015-06-18 04:40:53

标签: python sqlalchemy

我一直在关注SQLAlchemy对象关系教程(http://docs.sqlalchemy.org/en/latest/orm/tutorial.html),我创建了table_def.py,这是一个指定包含Player对象的表的文件(在我的例子中):

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Player(Base):
    """"""
    __tablename__ = "players"
    id = Column(Integer, primary_key=True)
    firstName = Column(String)
    lastName = Column(String)
    college = Column(String)
    ranking = Column(Integer)
    rating = Column(Float)

def __init__(self, rating, college, firstName=None, lastName=None, ranking=None):
    """"""
    self.rating = rating
    self.college = college
    self.firstName = firstName
    self.lastName = lastName
    self.ranking = ranking

这似乎指明了SQLAlchemy需要了解的有关玩家对象的所有内容。但是,我还有一个classes.py文件,其中包含:

class Player:
    def __init__(self,  rating, college, ranking = None, firstName = None, lastName = None):
        self.rating = rating
        self.college = college
        self.ranking = ranking
        self.firstName = firstName
        self.lastName = lastName

    def to_string(self):
        if self == None:
            return "None Object"
        rep = "firstName is " + self.firstName + " lastName is " + self.lastName + " rating is " + str(self.rating) + " college is " + self.college
        if self.ranking is not None:
            rep = " ranking is " + str(self.ranking) + " " + rep
        return rep

我实际上能够在普通的Player对象上调用to_string()(在我使用数据库之前)。但是拥有Player类的这两个定义似乎也是重复的。

我做错了什么/我应该做些什么来避免这种情况?

谢谢, bclayman

1 个答案:

答案 0 :(得分:1)

不,你不需要两节课。您可以将to_string()方法添加到SQLAlchemy使用的方法中,并且需要修复代码中__init__的参数的顺序。