python - sqlalchemy many to one
迷茫
迷茫 2017-04-17 14:24:31
0
1
596
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
大家讲道理

The situation is the same as when a Post has multiple Tags.

--- Update

I found that I can’t write either, sweat

I thought it was a problem with Handling Multiple Join Paths. Conflicts can be avoided by specifying foreign_keys. relationship("Address",foreign_keys=[billing_address_id])

But it will not be written when there is only one foreign_keys.

python#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sqlalchemy import create_engine
engine = create_engine("mysql://root:root@localhost/think", echo=True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

from sqlalchemy import Column, Integer, SmallInteger, String , DateTime, ForeignKey
from sqlalchemy.orm import relationship, backref

from datetime import datetime

# Post
class Post(Base):
     __tablename__ = 'Post'
     id = Column(Integer, primary_key=True)
     title = Column(String(100), index=True)
     content = Column(String(100), index=True)
     pics = relationship("Pic", backref=backref('Post', order_by=id))

     date = Column(DateTime, default=datetime.now())


     def __init__(self, title, content):
         self.title = title
         self.content = content

     def __repr__(self):
         return "{title:%s,title_pic:%s,content:%s,content_pic:%s}" \
                % (self.title,self.pics[0],self.content,self.pics[1:])


# 图片
class Pic(Base):
    __tablename__ = 'Pic'
    id = Column(Integer, primary_key=True)
    name = Column(String(10), index=True, unique=True)
    data = Column(String(100), index=True, unique=True)
    post_id = Column(Integer, ForeignKey('Post.id'))

    def __init__(self, name, data):
        self.name = name
        self.data = data

    def __repr__(self):
         return "{name:%s,data:%s}" % (self.name,self.data)


if '__main__' == __name__ :

    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind=engine)
    session = Session()

    # 1
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)

    # 2
    one = Post("h1", "lalala")
    one.pics.append(Pic("title_pic","img0.bmp"))
    one.pics.append(Pic("p0","img1.bmp"))
    one.pics.append(Pic("p1","img2.bmp"))
    one.pics.append(Pic("p2","img3.bmp"))

    two = Post("h2", "hahaha")
    two.pics.append(Pic("title_pic2","img20.bmp"))
    two.pics.append(Pic("p20","img21.bmp"))
    two.pics.append(Pic("p21","img22.bmp"))
    two.pics.append(Pic("p22","img23.bmp"))


    session.add_all([one,two])
    session.commit()

    # 3
    ret = session.query(Post).filter(Post.title == "h2").one()
    print ret


    session.close()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template