[英]How to update properly tags on a blog post in Flask app?
I have a taking notes system where each note can be associate with one or many tags.我有一个笔记系统,其中每个笔记都可以与一个或多个标签相关联。
Here is my model for that part:这是我的 model 部分:
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey(
'tag.id'), primary_key=True),
db.Column('notes_id', db.Integer, db.ForeignKey(
'notes.id'), primary_key=True)
)
class Notes(db.Model):
id = db.Column(db.Integer, primary_key=True)
# ...
tags = db.relationship('Tag', secondary=tags, lazy='subquery',
backref=db.backref('notes', lazy=True))
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=None)
def __init__(self, name):
self.name = name
I would like to remove the tags that are no longer associated with my note when I update this note.我想在更新此笔记时删除不再与我的笔记关联的标签。 How can I do that?
我怎样才能做到这一点?
For instance, it's what I have:例如,这就是我所拥有的:
@bp.route('/update/<int:id>', methods=['GET', 'POST'])
@login_required
def update(id):
note = Notes.query.get_or_404(id)
tags = []
for e in note.tags:
tag = Tag.query.get_or_404(e.id)
tags.append(tag.name)
tags = ', '.join(tags)
if request.method == 'POST':
note.title = request.form.get('title')
note.content = request.form.get('content')
note.updated_at = datetime.now()
# Get a tags list from an input and convert it to string
tags = request.form.get('tags').split(', ')
if tags:
for tag in tags:
tag_exists = Tag.query.filter_by(name=tag).first()
if not tag_exists:
new_tag = Task(tag)
db.session.add(new_tag)
note.tags.append(new_tag)
else:
db.session.add(tag_exists)
note.tags.append(tag_exists)
# Want to check if I have to delete tags associations here..
db.session.add(note)
db.session.commit()
return redirect(url_for('notes.index'))
else:
if note.owner_id == int(current_user.get_id()):
return render_template('notes/update.html', note=note, tags=tags)
else:
flash("You can't update a page which is not yours", "error")
return redirect(url_for('notes.index'))
I know my code is a bit dirty but it's my first real app with Flask, I do my best我知道我的代码有点脏,但这是我第一个使用 Flask 的真正应用程序,我尽我所能
Thank you for help谢谢你的帮助
Here is an example, hope this helps这是一个例子,希望这有帮助
# find note which you want change
note = Notes.query.get(3)
# find tag which you want delete
tag = note.tags[0]
note.tags.remove(tag)
db.session.add(note)
db.session.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.