My favorites | Sign in
Project Home
New issue   Search
for
  Advanced search   Search tips   Subscriptions

Issue 165 attachment: mapping.patch (2.7 KB)

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
commit 809f27fb1397c1a48b151919ce4c580b47dd5f6c
Author: Thomas Vander Stichele <thomas (at) apestaart (dot) org>
Date: Sat Apr 9 19:49:40 2011 +0200

Merge python-couchdb issue 165 for TupleField

diff --git a/paisley/mapping.py b/paisley/mapping.py
index df50206..c40d34a 100644
--- a/paisley/mapping.py
+++ b/paisley/mapping.py
@@ -68,7 +68,7 @@ from couchdb.design import ViewDefinition
__all__ = ['Mapping', 'Document', 'Field', 'TextField', 'FloatField',
'IntegerField', 'LongField', 'BooleanField', 'DecimalField',
'DateField', 'DateTimeField', 'TimeField', 'DictField', 'ListField',
- 'ViewField']
+ 'TupleField', 'ViewField']
__docformat__ = 'restructuredtext en'

DEFAULT = object()
@@ -747,3 +747,64 @@ class ListField(Field):

def pop(self, *args):
return self.field._to_python(self.list.pop(*args))
+
+class TupleField(Field):
+ """Field type for tuple of other fields, with possibly different types.
+
+ >>> from couchdb import Server
+ >>> server = Server('http://localhost:5984/')
+ >>> db = server.create('python-tests')
+
+ >>> class Post(Document):
+ ... title = TextField()
+ ... content = TextField()
+ ... pubdate = DateTimeField(default=datetime.now)
+ ... comments = ListField(TupleField((
+ ... TextField(),
+ ... TextField(),
+ ... DateTimeField()
+ ... )))
+
+ >>> post = Post(title='Foo bar')
+ >>> post.comments.append(('myself', 'Bla bla',
+ ... datetime.now()))
+ >>> len(post.comments)
+ 1
+ >>> post.store(db) #doctest: +ELLIPSIS
+ <Post ...>
+ >>> post = Post.load(db, post.id)
+ >>> comment = post.comments[0]
+ >>> comment[0]
+ u'myself'
+ >>> comment[1]
+ u'Bla bla'
+ >>> comment[2] #doctest: +ELLIPSIS
+ datetime.datetime(...)
+
+ >>> del server['python-tests']
+ """
+
+ def __init__(self, fields, name=None, default=None):
+ Field.__init__(self, name=name,
+ default=default or (None, ) * len(fields))
+
+ res = []
+ for field in fields:
+ if type(field) is type:
+ if issubclass(field, Field):
+ field = field()
+ elif issubclass(field, Mapping):
+ field = DictField(field)
+ res.append(field)
+ self.fields = tuple(res)
+
+ def _to_python(self, value):
+ return tuple([self.fields[i]._to_python(m)
+ for i, m in enumerate(value)])
+
+ def _to_json(self, value):
+ # value is a tuple with python values to be converted
+ assert len(self.fields) == len(value)
+ return [self.fields[i]._to_json(m) for i, m in enumerate(value)]
+
+
Powered by Google Project Hosting