現在Flask と SQLAlchemy を使ってwebapp 作りに取り組んでいます
relationship から上手く参照できず、結果がNoneになってしまって困っています
python
1class User(UserMixin, db.Model): 2 id = db.Column(db.Integer, primary_key=True) 3 username = db.Column(db.String(64), index=True, unique=True) 4 photos = db.relationship('Photo', back_populates='user') 5 6class Photo(db.Model): 7 id = db.Column(db.Integer, primary_key=True) 8 user_id = db.Column(db.Integer, db.ForeignKey('user.id')) 9 user = db.relationship('User', back_populates='photos')
テーブルはこのような感じです
例えばPhoto のusername を参照し、webに表示したいのですが
python
1@app.route('/') 2@app.route('/index') 3def index(): 4 photos = Photo.query.with_entities(Photo.id, Photo.name, Photo.image, Photo.user).all() 5 return render_template('index.html', title='Home',photos=photos) 6
html
1{% for photo in photos %} 2{{ photo.user.username }} 3{% endfor %}
追記
REPLでの参照は出来たのですが、やはりweb上でデータを操作すると参照ができないです
もしかしたら何か根本的に勘違いしているかもしれません
REPLでの参照方法は(念のため書いておくと)
python
1>>>u = User(username=...) 2>>>p = Photo(photo_name=..., user=u) 3>>>print(p.id, p.user.username, p.photo_name) 4... 5... 61 username photo_name
というような感じです
何か原因に心当たりのある方いれば回答お待ちしています
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/03/27 02:40
2018/03/27 02:42
退会済みユーザー
2018/03/27 02:46
2018/03/27 03:12 編集
退会済みユーザー
2018/03/27 03:24
退会済みユーザー
2018/03/27 03:28
2018/03/27 04:18
退会済みユーザー
2018/03/27 05:01
2018/03/27 05:11