首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何按类别添加自增字段

如何按类别添加自增字段
EN

Stack Overflow用户
提问于 2019-07-04 16:02:18
回答 1查看 20关注 0票数 0

我想为我的帖子表设置一个子id。此表已有一个id字段作为主要字段。但是帖子是有分类的。我想在每个类别的帖子作为自我增加的sub_id。

我正在写我的博客。Post具有PostCategory,PostCategory到Post是一对多关系。

代码语言:javascript
复制
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    # I tried this, but this did not work
    sub_id = db.Column(db.Integer, nullable=True, default=int(f'select count(*) from post where category_id={category_id}')+1)
    title = db.Column(db.String(120), unique=True, nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    # user in Foreignkey is table name
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    category_id = db.Column(db.Integer, db.ForeignKey('post_category.id'), nullable=False)

    def post_content_render_markdown(self):
        return markdown(self.content, extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
            ])

    def __repr__(self):
        return f"Post('{self.title}', {self.category.name}, '{self.date_posted}')"
代码语言:javascript
复制
class PostCategory(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), unique=True, nullable=False)
    description = db.Column(db.Text, nullable=False)
    posts = db.relationship('Post', backref='category', lazy=True)

    def __repr__(self):
        return f"Post Category('{self.id}', '{self.name}')"

错误消息

代码语言:javascript
复制
sub_id = db.Column(db.Integer, nullable=True, default=int(f'select count(*) from post where category_id={category_id}')+1)
NameError: name 'category_id' is not defined
EN

回答 1

Stack Overflow用户

发布于 2019-07-04 20:27:22

还有另一个现有的论点可以增加你的sub_id https://docs.sqlalchemy.org/en/13/core/defaults.html#python-executed-functions

代码语言:javascript
复制
sub_id = db.Column(db.Integer, nullable=True, autoincrement=True)

试试这个

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56883301

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档