1 | from sqlalchemy import Column, Date, ForeignKey, Integer, Unicode, func |
||
2 | from sqlalchemy.ext.declarative import declarative_base |
||
3 | from sqlalchemy.orm import (backref, column_property, relationship, |
||
4 | scoped_session, sessionmaker) |
||
5 | from zope.sqlalchemy import ZopeTransactionExtension |
||
6 | |||
7 | DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) |
||
8 | |||
9 | Base = declarative_base() |
||
10 | |||
11 | |||
12 | class User(Base): |
||
13 | """Define a User.""" |
||
14 | |||
15 | __tablename__ = "users" |
||
16 | |||
17 | id = Column(Integer, primary_key=True) |
||
18 | |||
19 | name = Column(Unicode, unique=True) |
||
20 | |||
21 | birthday = Column(Date) |
||
22 | |||
23 | address = relationship("Address", uselist=False, backref=backref("user")) |
||
24 | |||
25 | age = column_property( |
||
26 | func.strftime("%Y.%m%d", "now") - |
||
27 | func.strftime("%Y.%m%d", birthday).cast(Integer)) |
||
28 | |||
29 | def __unicode__(self): |
||
30 | """Give a readable representation of an instance.""" |
||
31 | return "%s" % self.name |
||
32 | |||
33 | def __repr__(self): |
||
34 | """Give a unambiguous representation of an instance.""" |
||
35 | return "<%s#%s>" % self.__class__.__name__, self.id |
||
36 | |||
37 | |||
38 | View Code Duplication | class Address(Base): |
|
0 ignored issues
–
show
Duplication
introduced
by
Loading history...
|
|||
39 | """Define an Address.""" |
||
40 | |||
41 | __tablename__ = "addresses" |
||
42 | |||
43 | id = Column(Integer, primary_key=True) |
||
44 | |||
45 | description = Column(Unicode, unique=True) |
||
46 | |||
47 | user_id = Column(Integer, ForeignKey("users.id")) |
||
48 | |||
49 | def __unicode__(self): |
||
50 | """Give a readable representation of an instance.""" |
||
51 | return "%s" % self.id |
||
52 | |||
53 | def __repr__(self): |
||
54 | """Give a unambiguous representation of an instance.""" |
||
55 | return "<%s#%s>" % self.__class__.__name__, self.id |
||
56 |