Sadece sqlalchemy öğrenmek için bir adres defteri basit bir veritabanı üzerinde çalışıyorum.SQLAlchemy ve Object Rlational içinde sıkışmış
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import Column, Integer, String, create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
engine = create_engine('sqlite:///phone.db', echo=True)
Base = declarative_base()
class namesT(Base):
__tablename__ = 'Names'
id = Column(Integer, primary_key=True)
name = Column(String)
sirname = Column(String)
job = Column(String)
work = Column(String)
def __init__(self, namesTuple):
self.name, self.sirname, self.job, self.work = namesTuple
print self.name, self.sirname, self.job, self.work
def __repr__(self):
return '%s, %s, %s, %s' % (self.name, self.sirname, self.job, self.work)
class detailT(Base):
__tablename__ = "Details"
id = Column(Integer, primary_key=True)
names_id = Column(Integer, ForeignKey('Names.id'))
type = Column(String)
info = Column(String)
detail = Column(String)
names = relationship(namesT, backref='Details', order_by=id, cascade="all, delete, delete-orphan")
def __init__(self, detailsTuple):
self.type, self.info, self.detail = detailsTuple
print self.type, self.info, self.detail
def __repr__(self):
return "%s, %s, %s" % (self.type, self.info, self.detail)
Base.metadata.create_all(engine)
Ve bu 'dbtrans.py' de şifre geçerli:: Bu 'tables.py' dosyası altında kodu (! Oldukça öğretici bir daha benzer) 'dir
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tables import engine as engine
from tables import namesT as names
from sqlalchemy.orm import sessionmaker
class transaction:
def __init__(self):
self.Session = sessionmaker(bind=engine)
self.session = self.Session()
def insert_in_names(self, namesTuple):
print namesTuple
ed = names(namesTuple)
self.session.add(ed)
def find(self):
self.session.query(names).filter(names.name=='ed').all()
def commitAll(self):
self.session.commit()
if __name__ == "__main__":
tup = ('Blah', 'Blah', 'Blah', 'Blah')
ins = transaction()
ins.insert_in_names(tup)
# print ins.sessQuery()
ins.commitAll()
sadece dbtrans çalıştırmak bu hatayı her zaman olsun:
sqlalchemy.orm.exc.FlushError: Instance <namesT at 0x14538d0> is an unsaved, pending instance and is an orphan (is not attached to any parent 'detailT' instance via that classes' 'names' attribute)
sorundur?
Haklısınız! Teşekkürler! – ArashM
Arash M, eğer haklılarsa, cevaplarını doğru olarak seçtiniz :) –