我想为我的帖子表设置一个子id。此表已有一个id字段作为主要字段。但是帖子是有分类的。我想在每个类别的帖子作为自我增加的sub_id。
我正在写我的博客。Post具有PostCategory,PostCategory到Post是一对多关系。
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}')"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}')"错误消息
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发布于 2019-07-04 20:27:22
还有另一个现有的论点可以增加你的sub_id https://docs.sqlalchemy.org/en/13/core/defaults.html#python-executed-functions
sub_id = db.Column(db.Integer, nullable=True, autoincrement=True)试试这个
https://stackoverflow.com/questions/56883301
复制相似问题