-
Notifications
You must be signed in to change notification settings - Fork 68
/
repr.py
60 lines (41 loc) · 1.3 KB
/
repr.py
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
53
54
55
56
57
58
59
60
from __future__ import print_function
import sqlalchemy as sa
from sqlalchemy.orm import scoped_session, sessionmaker, DeclarativeBase
from sqlalchemy_mixins import ReprMixin
class Base(DeclarativeBase):
__abstract__ = True
engine = sa.create_engine('sqlite:///:memory:')
session = scoped_session(sessionmaker(bind=engine))
class BaseModel(Base, ReprMixin):
__abstract__ = True
__repr__ = ReprMixin.__repr__
pass
class User(BaseModel):
__tablename__ = 'user'
__repr_attrs__ = ['name']
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
posts = sa.orm.relationship('Post', backref='user')
class Post(BaseModel):
__tablename__ = 'post'
__repr_attrs__ = ['body', 'user']
__repr_max_length__ = 25
id = sa.Column(sa.Integer, primary_key=True)
body = sa.Column(sa.String)
user_id = sa.Column(sa.Integer, sa.ForeignKey('user.id'))
Base.metadata.create_all(engine)
bob = User(name='Bob')
session.add(bob)
session.flush()
post1 = Post(body='Post 1', user=bob)
session.add(post1)
session.flush()
post2 = Post(body='Post 2 long-long body', user=bob)
session.add(post2)
session.flush()
# <User #1 'Bob'>
print(bob)
# <Post #1 body: 'Post 1' user: <User #1 ...>
print(post1)
# <Post #2 body: 'Post 2 long-...' user: <User #1 ...>
print(post2)