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 3 years, 10 months ago
  2. Yet another SQL debugging facility by miracle2k 6 years, 8 months ago
  3. Template filter that divides a list into exact columns by davmuz 2 years, 3 months ago
  4. UTC DateTime field by ludo 6 years, 7 months ago
  5. Tags & filters for rendering search results by exogen 6 years ago

Comments

(Forgotten your password?)