-
-
Save skyl/412750 to your computer and use it in GitHub Desktop.
from djredis.models import DredisMixin | |
import djredis.models | |
class Blog(models.Model, DredisMixin): # inherit from the mixin class | |
author = models.ForeignKey('Author') | |
title = models.CharField(max_length=200) | |
# declaratively add your redis fields | |
viewcount = djredis.models.Counter() | |
myzset = djredis.models.Zset() | |
>>> blog = Blog.objects.get(pk=1) | |
>>> blog.viewcount.incr() | |
1 | |
>>> blog.viewcount.incr(5) | |
6 | |
>>> blog.myzset | |
<SortedSet: []> | |
>>> blog.myzset.add('foo', 10) | |
True | |
>>> blog.myzset | |
<SortedSet: ['foo']> |
You don't need to make Counter itself a descriptor. If it's an object that has a contribute_to_class method, ModelBase will call that, and you can attach a descriptor that way. And contribute_to_class does get access to the attname.
(To be clear, you could make Counter itself the descriptor if you want to, as long as it also has the contribute_to_class method so you get the attname. But you could also make some other object be the descriptor; depends what makes for nicer code).
This is now implemented in my descriptor branch, but what about the cls/table - level fields? What would the usage of the api look like?
Should work pretty much the same, right? Except you'd access it via the class object rather than an instance.
If certain attributes only make sense to use at the class level, or vice versa, it's pretty easy to check for that in a descriptor (since get gets both instance and class args) and error out if it's being called the wrong way.
if Counter is a descriptor, there is no way to access the string "viewcount" to build the key behind the scenes.