通过Flask显示朋友的名字多对多的sqlalchemy

编程入门 行业动态 更新时间:2024-10-26 14:41:05
本文介绍了通过Flask显示朋友的名字多对多的sqlalchemy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有可以交朋友的应用程序,我可以算作朋友,并显示在profile.html但是,当我尝试打印朋友的名字它不起作用(它使用flask-sqlalchemy)

I have app that can make friends I am able to count friends and display it in profile.html But when I try to print the name of friends It doesn't work(It use flask-sqlalchemy)

model.py:

model.py:

friends = db.Table('friends', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('friend_id', db.Integer, db.ForeignKey('user.id')) ) class User(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(50), index=True, unique= True) email = db.Column(db.String(50),index=True, unique= True) is_friend = db.relationship('User', #defining the relationship, User is left side entity secondary = friends, primaryjoin = (friends.c.user_id == id), secondaryjoin = (friends.c.friend_id == id), backref = db.backref('friends', lazy = 'dynamic'), lazy = 'dynamic' )

py:

view.py:

@app.route('/profile/<int:id>') def profile(id): user= User.query.get(id) return render_template('profile.html', id=id, user= user)

profile.html:

profile.html:

{% extends "base.html" %} {% block content %} <strong>name:</strong> {{user.name}} <br> <strong>email:</strong> {{user.email }} <br> <strong>age:</strong> {{user.age}} <br> <br> # it shows the number of friends <p>{{ user.is_friend.count() }} friends <p> # Am I doing it right?if so why it doesn't show the name of friends? <p>{{ user.is_friend.name }} is friend</p> {% endblock %}

推荐答案

你选择了 is_friend ,可能会导致你的一些混淆。诸如 friends 之类的东西有点清晰。因为每个用户已经有关系,所以您也不需要返回引用。

The name you've chosen, is_friend, is probably causing some of your confusion. Something like friends is a bit clearer. You also don't need the back reference as each User already has the relationship.

class User(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(50), index=True, unique= True) email = db.Column(db.String(50),index=True, unique= True) friends = db.relationship('User', #defining the relationship, User is left side entity secondary = friends, primaryjoin = (friends.c.user_id == id), secondaryjoin = (friends.c.friend_id == id), lazy = 'dynamic' )

该关系为您提供了一个查询集,您可以迭代获取所有相关记录。

The relationship gives you a query set that you can iterate over to get all of the related records.

{% for friend in user.friends %} <p>{{ friend.name }} is friend.</p> {% endfor %}

更多推荐

通过Flask显示朋友的名字多对多的sqlalchemy

本文发布于:2023-10-26 22:04:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名字   朋友   Flask   sqlalchemy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!