Per-Instance On-Model M2M Caching

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Necklace(models.Model):
    
    ### FIELDS ###
    
    ...

    beads = models.ManyToManyField(Bead, through="BeadSet", blank=True)
    
    ...
    
    ### CACHING METHODS ###
    
    def get_beadsets(self): # cache beadsets query to _beadsets
        try:
            _check = self._beadsets
        except:
            self._beadsets = BeadSet.objects.filter(necklace=self).select_related()
        return self._beadsets
    
    def get_beads(self): # cache beads query to _beads
        try:
            _check = self._beads
        except:
            self._beads = self.beads.all().select_related()
        return self._beads
    
    ...

More like this

  1. load m2m fields objects by dirol 2 years, 11 months ago
  2. Template filter that divides a list into exact columns by davmuz 1 year, 4 months ago
  3. Active page class for selected menu items by kunitoki 7 months, 3 weeks ago
  4. Form rendering using a template instead of builtin HTML by leoh 5 years, 11 months ago
  5. Yet another SQL debugging facility by miracle2k 5 years, 9 months ago

Comments

Klaidi (on July 22, 2010):

Nice one!

#

(Forgotten your password?)