본문 바로가기

Dev./Google App Engine

Datastore - NDB API(Python) : Property Type


NDB에서 사용하는 Property Types

Property typeDescription
IntegerProperty64-bit signed integer
FloatPropertyDouble-precision floating-point number
BooleanPropertyBoolean
StringPropertyUnicode string; up to 500 characters, indexed
TextPropertyUnicode string; unlimited length, not indexed
BlobPropertyUninterpreted byte string:
if you set indexed=True, up to 500 characters, indexed;
if indexed is False (the default), unlimited length, not indexed.
Optional keyword argument: compressed.
DateTimePropertyDate and time (see Date and Time Properties)
DatePropertyDate (see Date and Time Properties)
TimePropertyTime (see Date and Time Properties)
GeoPtPropertyGeographical location. This is a ndb.GeoPt object. The object has attributes 
lat and lon, both floats. You can construct one with two floats like
 ndb.GeoPt(52.37, 4.88) or with a string
 ndb.GeoPt("52.37, 4.88"). (This is actually the same class as db.GeoPt)
KeyPropertyDatastore key
Optional keyword argument: kind=kind, to require that keys assigned to
this property always have the indicated kind. May be a string or a Model subclass.
BlobKeyPropertyBlobstore key
Corresponds to BlobReferenceProperty in the old db API,
but the property value is a BlobKey instead of a BlobInfo;
you can construct a BlobInfo from it using BlobInfo(blobkey)
UserPropertyUser object.
StructuredPropertyIncludes one kind of model inside another, by value (see Structured Properties)
LocalStructuredPropertyLike StructuredProperty, but on-disk representation is an opaque blob
and is not indexed (see Structured Properties).
Optional keyword argument: compressed.
JsonPropertyValue is a Python object (such as a list or a dict or a string)
that is serializable using Python's json module;
the Datastore stores the JSON serialization as a blob. Unindexed by default.
Optional keyword argument: compressed.
PicklePropertyValue is a Python object (such as a list or a dict or a string)
that is serializable using Python's pickle protocol;
the Datastore stores the pickle serialization as a blob. Unindexed by default.
Optional keyword argument: compressed.
GenericPropertyGeneric value
Used mostly by the Expando class, but also usable explicitly. Its type may be any of intlongfloatboolstrunicodedatetime,KeyBlobKeyGeoPtUserNone.
ComputedPropertyValue computed from other properties by a user-defined function.
(See Computed Properties.)

출처 : https://developers.google.com/appengine/docs/python/ndb/properties



Property가 가질수 있는 Options

ArgumentTypeDefaultDescription
indexedboolUsuallyTrueInclude property in Datastore's indexes; if False,
values cannot be queried but writes are faster.
Not all property types support indexing;
setting indexed to True fails for these.
Unindexed properties cost fewer write ops
than indexed properties.
repeatedboolFalseProperty value is a Python list containing values of
the underlying type (see Repeated Properties).
requiredboolFalseProperty must have a value specified.
Cannot be combined with repeated=True 
but can be combined with default=True.
defaultProperty's underlying typeNoneDefault value of property if none explicitly specified.
Cannot be combined with repeated=True 
but can be combined with required=True.
choicesList of values of underlying typeNoneOptional list of allowable values.
validatorFunctionNone

Optional function to validate and possibly coerce the value.

Will be called with arguments (propvalue) and should either return 

the (possibly coerced) value or raise an exception. 

Calling the function again on a coerced value should not 

modify the value further. 

(For example, returning value.strip() orvalue.lower() is fine, 

but not value + '$'.) 

May also return None, which means "no change". 

See also Writing Property Subclasses

verbose_namestringNone

Optional HTML label to use in web form frameworks like jinja2.

출처 : https://developers.google.com/appengine/docs/python/ndb/properties




repeated (option)

복수의 데이터를 입력할때 사용된다. list 형태로 입력, 조회 된다.

class Article(ndb.Model):
    title = ndb.StringProperty()
    stars = ndb.IntegerProperty()
    tags = ndb.StringProperty(repeated=True)

art = Article(title='Python versus Ruby',
              stars=3,
              tags=['python', 'ruby'])
art.put()

뭐 이런식으로....




DateTimeProperty(DateProperty, TimeProperty)

DateTimeProperty는  date와 time 을 기록

DateProperty는 date만 기록

TimeProperty는 time만 기록

python 의 datetime 모듈로 매핑된다.

auto_now, auto_now_add 속성이 있는데

auto_now_add 속성을 True로 하면 데이터가 입력될 때만 현재시간 (UTC)을 입력하고

auto_now 속성을 True로 하면 입력, 수정 될 때마다 값이 자동으로 입력된다.


사용 예는

class Article(ndb.Model):

    title = ndb.StringProperty()
    stars = ndb.IntegerProperty()
    tags = ndb.StringProperty(repeated=True)
    date_time = ndb.DateTimeProperty(auto_now_add=True)

대충 위 처럼 사용하면 된다.



Structured Properties

string, int 이런 데이터 타입이 아닌 model 을 property로 사용 할 수 있다.

간단히 예를 보면

class Address(ndb.Model):
    type = ndb.StringProperty()
    street = ndb.StringProperty()
    city = ndb.StringProperty()
    
class Contact(ndb.Model):
    name = ndb.StringProperty()
    addresses = ndb.StructuredProperty(Address, repeated=True)

guido = Contact(name='Giudo',
                addresses=[Address(type='home', city='Amsterdam'),
                           Address(type='work', street='Spear St', city='SF')])
        
guido.put()

위와 같이 Contact 모델이 Address 모델을 property로 가질 수 있다.




Computed Properties

property를 지정하지 않고 다른 property를 이용해서 property를 만드는 타입

class SomeEntity(ndb.Model):
    name = ndb.StringProperty()
    name_lower = ndb.ComputedProperty(lambda self: self.name.lower())

x = SomeEntity(name='Nick')
#name = 'Nick'
#name_lower = 'nick'

위와 같이 name property를 할당하면 이걸 가지고 name_lower을 만들어 낸다.



반응형