Object Relation Manager¶
Redisco allows you to store objects in Redis. Redisco can easily manage object creation, update and deletion. It is strongly Ohm and Django ORM and try to provide a simple approach.
>>> from redisco import models
>>> class Person(models.Model):
... name = models.Attribute(required=True)
... created_at = models.DateTimeField(auto_now_add=True)
... fave_colors = models.ListField(str)
>>> person = Person(name="Conchita")
>>> person.is_valid()
True
>>> person.save()
True
>>> conchita = Person.objects.filter(name='Conchita')[0]
>>> conchita.name
'Conchita'
>>> conchita.created_at
datetime.datetime(2010, 5, 24, 16, 0, 31, 954704)
Model¶
The Model
class is the class that will contain your object. It upports many different type of attributes and support custom object validation to ensure data integrity when saving.
-
class
redisco.models.
Model
(**kwargs)¶ -
attributes
¶ Return the attributes of the model.
Returns a dict with models attribute name as keys and attribute descriptors as values.
-
attributes_dict
¶ Returns the mapping of the model attributes and their values.
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... title = models.Attribute() ... >>> f = Foo(name="Einstein", title="Mr.") >>> f.attributes_dict {'name': 'Einstein', 'title': 'Mr.'}
-
counters
¶ Returns the mapping of the counters.
-
db
¶ Returns the Redis client used by the model.
-
decr
(att, val=1)¶ Decrements a counter.
>>> from redisco import models >>> class Foo(models.Model): ... cnt = models.Counter() ... >>> f = Foo() >>> f.save() True >>> f.incr('cnt', 10) >>> f.cnt 10 >>> f.decr('cnt', 2) >>> f.cnt 8 >>> f.delete()
-
delete
()¶ Deletes the object from the datastore.
-
errors
¶ Returns the list of errors after validation.
-
classmethod
exists
(id)¶ Checks if the model with id exists.
-
fields
¶ Returns the list of field names of the model.
-
id
¶ Returns the id of the instance.
Raises MissingID if the instance is new.
-
incr
(att, val=1)¶ Increments a counter.
>>> from redisco import models >>> class Foo(models.Model): ... cnt = models.Counter() ... >>> f = Foo() >>> f.save() True >>> f.incr('cnt', 10) >>> f.cnt 10 >>> f.delete()
-
indices
¶ Return a list of the indices of the model. ie: all attributes with index=True.
-
is_new
()¶ Returns True if the instance is new.
Newness is based on the presence of the _id attribute.
-
is_valid
()¶ Returns True if all the fields are valid.
It first validates the fields (required, unique, etc.) and then calls the validate method.
>>> from redisco import models >>> def validate_me(field, value): ... if value == "Invalid": ... return (field, "Invalid value") ... >>> class Foo(models.Model): ... bar = models.Attribute(validator=validate_me) ... >>> f = Foo() >>> f.bar = "Invalid" >>> f.save() ['bar', 'Invalid value']
Warning
You may want to use
validate
described below to validate your model
-
key
(att=None)¶ Returns the Redis key where the values are stored.
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... title = models.Attribute() ... >>> f = Foo(name="Einstein", title="Mr.") >>> f.save() True >>> f.key() == "%s:%s" % (f.__class__.__name__, f.id) True
-
lists
¶ Returns the lists of the model.
Returns a dict with models attribute name as keys and ListField descriptors as values.
-
references
¶ Returns the mapping of reference fields of the model.
-
save
()¶ Saves the instance to the datastore with the following steps: 1. Validate all the fields 2. Assign an ID if the object is new 3. Save to the datastore.
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... title = models.Attribute() ... >>> f = Foo(name="Einstein", title="Mr.") >>> f.save() True >>> f.delete()
-
update_attributes
(**kwargs)¶ Updates the attributes of the model.
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... title = models.Attribute() ... >>> f = Foo(name="Einstein", title="Mr.") >>> f.update_attributes(name="Tesla") >>> f.name 'Tesla'
-
validate
()¶ Overriden in the model class. The function is here to help you validate your model. The validation should add errors to self._errors.
Example:
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute(required=True) ... def validate(self): ... if self.name == "Invalid": ... self._errors.append(('name', 'cannot be Invalid')) ... >>> f = Foo(name="Invalid") >>> f.save() [('name', 'cannot be Invalid')]
-
Attributes¶
The attributes are the core of any redisco Model
. Many different attributes are available according to your needs. Read the following documentation to understand the caveats of each attribute.
- Attribute
- Stores unicode strings. If used for large bodies of text, turn indexing of this field off by setting indexed=True.
- IntegerField
- Stores an int. Ints are stringified using unicode() before saving to Redis.
- Counter
- An IntegerField that can only be accessed via Model.incr and Model.decr.
- DateTimeField
- Can store a DateTime object. Saved in the Redis store as a float.
- DateField
- Can store a Date object. Saved in Redis as a float.
- FloatField
- Can store floats.
- BooleanField
- Can store bools. Saved in Redis as 1’s and 0’s.
- ReferenceField
- Can reference other redisco model.
- ListField
- Can store a list of unicode, int, float, as well as other redisco models.
Attribute Options¶
- required
- If True, the attirbute cannot be None or empty. Strings are stripped to check if they are empty. Default is False.
- default
- Sets the default value of the attribute. Default is None.
- indexed
- If True, redisco will create index entries for the attribute. Indexes are used in filtering and ordering results of queries. For large bodies of strings, this should be set to False. Default is True.
- validator
- Set this to a callable that accepts two arguments – the field name and the value of the attribute. The callable should return a list of tuples with the first item is the field name, and the second item is the error.
- unique
- The field must be unique. Default is False.
DateField and DateTimeField Options
- auto_now_add
- Automatically set the datetime/date field to now/today when the object is first created. Default is False.
- auto_now
- Automatically set the datetime/date field to now/today everytime the object is saved. Default is False.
Modelset¶
The ModelSet
class is useful for all kind of queries when you want to filter data (like in SQL). You can filter objects by values in their attributes, creation dates and even perform some unions and exclusions.
>>> from redisco import models
>>> class Person(models.Model):
... name = models.Attribute(required=True)
... created_at = models.DateTimeField(auto_now_add=True)
... fave_colors = models.ListField(str)
>>> person = Person(name="Conchita")
>>> person.save()
True
>>> conchita = Person.objects.filter(name='Conchita').first()
-
class
redisco.models.modelset.
ModelSet
(model_class)¶ -
all
()¶ Return all elements of the collection.
-
exclude
(**kwargs)¶ Exclude a collection within a lookup.
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... exclude_me = models.BooleanField() ... >>> Foo(name="Einstein").save() True >>> Foo(name="Edison", exclude_me=True).save() True >>> Foo.objects.exclude(exclude_me=True).first().name u'Einstein' >>> [f.delete() for f in Foo.objects.all()] [...]
-
filter
(**kwargs)¶ Filter a collection on criteria
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... >>> Foo(name="toto").save() True >>> Foo(name="toto").save() True >>> Foo.objects.filter() [<Foo:...>, <Foo:...>] >>> [f.delete() for f in Foo.objects.all()] [...]
-
first
()¶ Return the first object of a collections.
Returns: The object or Non if the lookup gives no result >>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... >>> f = Foo(name="toto") >>> f.save() True >>> Foo.objects.filter(name="toto").first() <Foo:...> >>> [f.delete() for f in Foo.objects.all()] [...]
-
get_by_id
(id)¶ Returns the object definied by
id
.Parameters: id – the id
of the objects to lookup.Returns: The object instance or None if not found. >>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... >>> f = Foo(name="Einstein") >>> f.save() True >>> Foo.objects.get_by_id(f.id) == f True >>> [f.delete() for f in Foo.objects.all()] [...]
-
get_or_create
(**kwargs)¶ Return an element of the collection or create it if necessary.
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... >>> new_obj = Foo.objects.get_or_create(name="Obama") >>> get_obj = Foo.objects.get_or_create(name="Obama") >>> new_obj == get_obj True >>> [f.delete() for f in Foo.objects.all()] [...]
-
limit
(n, offset=0)¶ Limit the size of the collection to n elements.
-
order
(field)¶ Enable ordering in collections when doing a lookup.
Warning
This should only be called once per lookup.
>>> from redisco import models >>> class Foo(models.Model): ... name = models.Attribute() ... exclude_me = models.BooleanField() ... >>> Foo(name="Abba").save() True >>> Foo(name="Zztop").save() True >>> Foo.objects.all().order("-name").first().name u'Zztop' >>> Foo.objects.all().order("name").first().name u'Abba' >>> [f.delete() for f in Foo.objects.all()] [...]
-