-
Notifications
You must be signed in to change notification settings - Fork 0
/
adding_records_to_table.txt
52 lines (38 loc) · 1.02 KB
/
adding_records_to_table.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database
adding records to table
1. get into the python shell
>>> from api import create_app
>>> app = create_app()
>>> app.app_context().push()
>>> from api import db
>>> from api.models import User, Post
>>> u = User(username='john', email='john@example.com')
>>> db.session.add(u)
>>> db.session.commit()
Query User Table
>>> users = User.query.all()
>>> users
>>> for u in users:
...[tab] print(u.id, u.username)
...[enter]
Now let's add a blog post:(adding a shop review)
>>> u = User.query.get(1)
>>> p = Post(body='my first post!', author=u)
>>> db.session.add(p)
>>> db.session.commit()
Query Post Table
>>> posts = Post.query.all()
>>> posts
To get Post Object
>>> p = posts[0]
>>> p
>>> p.id
>>> p.author
To get list of user's posts>>> for p in u.posts:
... p
...
<Post my first coffee review!>
<Post my second post!>
# get all users in reverse alphabetical order
>>> User.query.order_by(User.username.desc()).all()
[<User susan>, <User john>]