Skip to content

Instantly share code, notes, and snippets.

@skyl
Forked from djfroofy/djredis_iface.py
Created May 25, 2010 04:09
Show Gist options
  • Select an option

  • Save skyl/412750 to your computer and use it in GitHub Desktop.

Select an option

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']>
@skyl

skyl commented May 25, 2010

Copy link
Copy Markdown
Author

if Counter is a descriptor, there is no way to access the string "viewcount" to build the key behind the scenes.

@carljm

carljm commented May 25, 2010

Copy link
Copy Markdown

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.

@carljm

carljm commented May 25, 2010

Copy link
Copy Markdown

(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).

@skyl

skyl commented May 26, 2010

Copy link
Copy Markdown
Author

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?

@carljm

carljm commented May 26, 2010

Copy link
Copy Markdown

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment