1

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?

DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
Mp0int
  • 18,172
  • 15
  • 83
  • 114
  • 2
    If you're caching the whole object, there's no point to the dictionary at all: just pass `aComp` to `cache.set`. – Daniel Roseman Jan 11 '12 at 11:24
  • @DanielRoseman - aComp 'd the Django qs object (no hit to DB yet i.e. queryset has yet to be evaluated). I tried setting obj, with cache.get('obj') resulted in same number of queries - as it got evaluated template i.e. obj.attr – Nabeel Ahmed Apr 25 '16 at 12:47
  • I am looking for a way to cache the expensive queries - with minimum dev overhead (a huge codebase). – Nabeel Ahmed Apr 25 '16 at 12:49

1 Answers1

2

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.

DrTyrsa
  • 31,014
  • 7
  • 86
  • 86