[英]How to update properly tags on a blog post in Flask app?
我有一個筆記系統,其中每個筆記都可以與一個或多個標簽相關聯。
這是我的 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
我想在更新此筆記時刪除不再與我的筆記關聯的標簽。 我怎樣才能做到這一點?
例如,這就是我所擁有的:
@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'))
我知道我的代碼有點臟,但這是我第一個使用 Flask 的真正應用程序,我盡我所能
謝謝你的幫助
這是一個例子,希望這有幫助
# 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.