python - 如何创建一对多关系表
阿神
阿神 2017-04-17 16:36:29
[Python讨论组]

看了官方文档,但是还是不太明白
想要实现一个简单的评论功能,一条评论对应多条回复

class Comments(db.Model):
    __bind_key__ = 'comments'
    __tablename__ = 'comments'
    id = db.Column(db.Integer,primary_key=True)
    comment_user = db.Column(db.String, nullable=False)
    comment_publish = db.Column(db.DateTime, nullable=False)
    comment_content = db.Column(db.Text,nullable=False)
    reply = db.relationship('Replies',backref='comments',lazy='dynamic')

    def __init__(self, comment_user,comment_content, comment_publish = datetime.datetime.now()):
        self.comment_user = comment_user
        self.comment_content = comment_content
        self.comment_publish = comment_publish

    def __repr__(self):
        return "<Comments %r>" % self.comment_content

class Replies(db.Model):
    __bind_key__ = 'replies'
    __tablename__ = 'replies'
    id = db.Column(db.Integer,primary_key=True)
    reply_user = db.Column(db.String, nullable=False)
    reply_publish = db.Column(db.DateTime, nullable=False)
    reply_content = db.Column(db.Text,nullable=False)
    comments_id = db.Column(db.Integer, db.ForeignKey('comments.id'))

    def __init__(self, reply_user,reply_content, reply_publish = datetime.datetime.now()):
        self.reply_user = reply_user
        self.reply_content = reply_content
        self.reply_publish = reply_publish

    def __repr__(self):
        return "<Replies %r>" % self.reply_content

不知道这样创建的是不是关系表,那插入数据时comments_id又该如何操作

阿神
阿神

闭关修行中......

全部回复(1)
巴扎黑

干嘛要用alchemy

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号