gpt4 book ai didi

python - 多对多表和初始化字段

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:03 27 4
gpt4 key购买 nike

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

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: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)

最佳答案

您必须使用Association Object .

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

关于python - 多对多表和初始化字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22090283/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com