多对多表和初始化字段

时间:2014-02-28 08:49:32

标签: python python-2.7 orm sqlalchemy

我想在多对多表中添加一些字段,当我使用这样的东西时:

test_server = FileServer('192.168.1.1', 80, 'online')
session.add(test_server)
session.commit()

test_file = File('test.txt', '123456.txt', hash('123456.txt'), 1024, 1)
session.add(test_file)
session.commit()

# add also initialize there for chunk_size, chunk_number; what also add there?
test_file.server_id.append(test_server)
session.commit()

还初始化chunk_number和chunk_size一些值。如何从SQLAlchemy做到这一点? 也许将m2m移到class,使用Base?

源代码:

from time import gmtime, strftime

import sqlamp
from sqlalchemy import create_engine, MetaData
from sqlalchemy import Integer, DateTime, Float, BigInteger, Boolean, String, Column, ForeignKey, Table
from sqlalchemy.orm import validates, relationship, relation
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('postgresql://user:test@localhost/csan')
metadata = MetaData(engine)
Base = declarative_base(metadata=metadata, metaclass=sqlamp.DeclarativeMeta)

m2m_file_server = Table('m2m_file_server', Base.metadata,
    Column('id', Integer, primary_key=True),
    Column('file_id', Integer, ForeignKey('file.id')),
    Column('server_id', Integer, ForeignKey('fileserver.id')),
    # additional fields
    Column('chunk_number', Integer, nullable=False)
    Column('chunk_size', Integer, nullable=False)
)


class File(Base):
    __tablename__ = 'file'
    id = Column(Integer, primary_key=True)
    original_name = Column(String, nullable=False)
    server_name = Column(String, nullable=False)
    file_hash = Column(String, nullable=False)
    filesize = Column(BigInteger)
    catalog_id = Column(Integer, ForeignKey("catalog.id"))
    server_id = relationship("FileServer", secondary=m2m_file_server)

    def __init__(self, orig_name, serv_name, file_hash, filesize, catalog_id):
        self.original_name = orig_name
        self.server_name = serv_name
        self.file_hash = file_hash
        self.filesize = filesize
        self.catalog_id = catalog_id

    def __repr__(self):
        return "<File('%s','%s','%s','%d')>" % (self.original_name, self.server_name, self.file_hash,
                                                     self.filesize)


class FileServer(Base):
    __tablename__ = 'fileserver'
    id = Column(Integer, primary_key=True)
    ip = Column(String, nullable=False)
    port = Column(Integer, nullable=False)
    status = Column(String)
    last_online = Column(DateTime)

    def __init__(self, ip, port, status):
        self.ip = ip
        self.port = port
        self.status = status
        self.last_online = strftime("%Y-%m-%d %H:%M:%S", gmtime())

    def __repr__(self):
        return "<FileServer('%s','%d','%s','%s')>" % (self.ip, self.port, self.status, self.last_online)

1 个答案:

答案 0 :(得分:1)

您必须使用Association Object

您必须创建新的Association类,该类将与idextra_fields两个表相关联。