2014-02-28 62 views
1

我想某些字段添加到使用這樣的事情多到許多表,當IM:許多一對多表和初始化領域

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移動到類,它使用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:[email protected]/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

你必須使用Association Object

您必須創建新的Association類,該類將與idextra_fields這兩個表相關聯。