|
| 1 | +# Copyright 2016 Google Inc. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from google.appengine.ext import ndb |
| 16 | + |
| 17 | + |
| 18 | +class Article(ndb.Model): |
| 19 | + title = ndb.StringProperty() |
| 20 | + author = ndb.StringProperty() |
| 21 | + tags = ndb.StringProperty(repeated=True) |
| 22 | + |
| 23 | + |
| 24 | +def print_author_tags(): |
| 25 | + query = Article.query() |
| 26 | + articles = query.fetch(20, projection=[Article.author, Article.tags]) |
| 27 | + for article in articles: |
| 28 | + print(article.author) |
| 29 | + print(article.tags) |
| 30 | + # article.title will raise a ndb.UnprojectedPropertyError |
| 31 | + |
| 32 | + |
| 33 | +class Address(ndb.Model): |
| 34 | + type = ndb.StringProperty() # E.g., 'home', 'work' |
| 35 | + street = ndb.StringProperty() |
| 36 | + city = ndb.StringProperty() |
| 37 | + |
| 38 | + |
| 39 | +class Contact(ndb.Model): |
| 40 | + name = ndb.StringProperty() |
| 41 | + addresses = ndb.StructuredProperty(Address, repeated=True) |
| 42 | + |
| 43 | + |
| 44 | +def fetch_sub_properties(): |
| 45 | + Contact.query().fetch(projection=["name", "addresses.city"]) |
| 46 | + Contact.query().fetch(projection=[Contact.name, Contact.addresses.city]) |
| 47 | + |
| 48 | + |
| 49 | +def demonstrate_ndb_grouping(): |
| 50 | + Article.query(projection=[Article.author], group_by=[Article.author]) |
| 51 | + Article.query(projection=[Article.author], distinct=True) |
| 52 | + |
| 53 | + |
| 54 | +class Foo(ndb.Model): |
| 55 | + A = ndb.IntegerProperty(repeated=True) |
| 56 | + B = ndb.StringProperty(repeated=True) |
| 57 | + |
| 58 | + |
| 59 | +def declare_multiple_valued_property(): |
| 60 | + entity = Foo(A=[1, 1, 2, 3], B=['x', 'y', 'x']) |
| 61 | + return entity |
0 commit comments