質問編集履歴

1

修正

2020/05/12 12:06

投稿

退会済みユーザー
test CHANGED
File without changes
test CHANGED
@@ -33,115 +33,3 @@
33
33
  parent_id = child.parent.id #<--- リレーションされているparentデータ取得失敗
34
34
 
35
35
  ```
36
-
37
-
38
-
39
- 全コード
40
-
41
- ```python
42
-
43
- from flask import Flask
44
-
45
- from flask_sqlalchemy import SQLAlchemy
46
-
47
-
48
-
49
- app = Flask(__name__)
50
-
51
- app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
52
-
53
- db = SQLAlchemy(app)
54
-
55
-
56
-
57
-
58
-
59
- def func():
60
-
61
- # 親データ追加
62
-
63
- parent = Parent('Test A', 'pass')
64
-
65
- db.session.add(parent)
66
-
67
- db.session.commit()
68
-
69
-
70
-
71
- # 子データの追加
72
-
73
- child = Child('ユーザー', 'パスワード', parent.id)
74
-
75
- db.session.bulk_save_objects([child], return_defaults=True)
76
-
77
- # 普通にaddするとうまくいく
78
-
79
- # db.session.add(child)
80
-
81
- db.session.commit()
82
-
83
- parent_id = child.parent.id
84
-
85
-
86
-
87
-
88
-
89
- class Parent(db.Model):
90
-
91
- __tablename__ = 'parent'
92
-
93
- id = db.Column(db.Integer, primary_key=True)
94
-
95
- username = db.Column(db.String(80))
96
-
97
- password = db.Column(db.String(80))
98
-
99
- child = db.relationship("Child", cascade="all, delete")
100
-
101
-
102
-
103
- def __init__(self, username, password):
104
-
105
- self.username = username
106
-
107
- self.password = password
108
-
109
-
110
-
111
-
112
-
113
- class Child(db.Model):
114
-
115
- __tablename__ = 'child'
116
-
117
- id = db.Column(db.Integer, primary_key=True)
118
-
119
- child_name = db.Column(db.String(80))
120
-
121
- password = db.Column(db.String(80))
122
-
123
- parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
124
-
125
- parent = db.relationship("Parent")
126
-
127
-
128
-
129
- def __init__(self, username, password, parent_id):
130
-
131
- self.parent_name = username
132
-
133
- self.password = password
134
-
135
- self.parent_id = parent_id
136
-
137
-
138
-
139
-
140
-
141
- app.debug = True
142
-
143
- db.create_all()
144
-
145
- func()
146
-
147
- ```