1
|
|
|
import datetime |
|
|
|
|
2
|
|
|
|
3
|
|
|
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, String, func |
4
|
|
|
from sqlalchemy.ext.declarative import declarative_base |
5
|
|
|
from sqlalchemy.ext.hybrid import hybrid_property |
6
|
|
|
from sqlalchemy.orm import backref, relationship |
7
|
|
|
|
8
|
|
|
Base = declarative_base() |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
class User(Base): |
|
|
|
|
12
|
|
|
"""Define a User.""" |
13
|
|
|
|
14
|
|
|
__tablename__ = 'users' |
15
|
|
|
|
16
|
|
|
id = Column(Integer, primary_key=True) |
|
|
|
|
17
|
|
|
name = Column(String, unique=True) |
18
|
|
|
created_at = Column(DateTime, default=datetime.datetime.utcnow) |
19
|
|
|
birthday = Column(Date) |
20
|
|
|
address = relationship('Address', uselist=False, backref=backref('user')) |
21
|
|
|
|
22
|
|
|
def __unicode__(self): |
23
|
|
|
"""Give a readable representation of an instance.""" |
24
|
|
|
return '%s' % self.name |
25
|
|
|
|
26
|
|
|
def __repr__(self): |
27
|
|
|
"""Give a unambiguous representation of an instance.""" |
28
|
|
|
return '<%s#%s>' % (self.__class__.__name__, self.id) |
29
|
|
|
|
30
|
|
|
@hybrid_property |
31
|
|
|
def dummy(self): |
32
|
|
|
"""Create a dummy hybrid property.""" |
33
|
|
|
return self.name[0:3] |
34
|
|
|
|
35
|
|
|
@dummy.expression |
36
|
|
|
def dummy(cls): |
|
|
|
|
37
|
|
|
"""Create a dummy expression.""" |
38
|
|
|
return func.substr(cls.name, 0, 3) |
39
|
|
|
|
40
|
|
|
|
41
|
|
View Code Duplication |
class Address(Base): |
|
|
|
|
42
|
|
|
"""Define an Address.""" |
43
|
|
|
|
44
|
|
|
__tablename__ = 'addresses' |
45
|
|
|
|
46
|
|
|
id = Column(Integer, primary_key=True) |
|
|
|
|
47
|
|
|
description = Column(String, unique=True) |
48
|
|
|
user_id = Column(Integer, ForeignKey('users.id')) |
49
|
|
|
|
50
|
|
|
def __unicode__(self): |
51
|
|
|
"""Give a readable representation of an instance.""" |
52
|
|
|
return '%s' % (self.id) |
53
|
|
|
|
54
|
|
|
def __repr__(self): |
55
|
|
|
"""Give a unambiguous representation of an instance.""" |
56
|
|
|
return '<%s#%s>' % (self.__class__.__name__, self.id) |
57
|
|
|
|
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.