pythondjangocachingmemcachedpython-memcached

Python Memcached: caching objects


I am using Python 2.6.5 and Django 1.3

Let me say i have model like:

class Company(models.Model):
    name = models.CharField(...)
    type = models.SmallIntegerField(...)
    ....

    def check_condition(self, someParam):
        do someThing...
        return someThing

This one is a heavily used model, so i keep basic data ina dictionary and cache this dictionary

aComp = Company.objects.get(pk=somevalue)
compDict = {'name':aComp.name, 'type': aComp.type...}
cache.set('companyInfo', compDict)

All is well, but in some conditions, i need to call methods of Company but since i cache company info , i wonder whether it is good to cache object or not... Like

compDict = {'name':aComp.name, 'type': aComp.type, 'obj':aComp}

And use it

myComp = cache.get('companyInfo')
compInst = myComp['obj']
compInst.check_condition(aParam)

And i wonder how effective it is to cache an object and used cached object for instance method calls like that?


Solution

  • There is no problems with it. Of course there will be some overhead of pickling object, not raw data, but you won't notice it.

    And remember, that when you access ForeignKey, ManyToManyField and OneToOneField, you will make DB hit anyway. But you can cache these relations manually.