PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 13, 2022

[FIXED] How should I generate cache keys

 November 13, 2022     caching, django, memcached     No comments   

Issue

I want to cache following models and a shortened link for each Question.

class Question(models.Model):
    question_text = models.CharField('text', max_length=200)
    pub_date = models.DateTimeField('publication date', default=timezone.now)
    allow_multiple_choices = models.BooleanField(default=False)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField('text', max_length=200)
    votes = models.IntegerField('votes', default=0)

    def __str__(self):
        return self.choice_text

How should I generate keys? Is something like this sufficient?

cache.set('question' + question.id, question)
cache.set('shortened' + question.id, shortened)

Solution

This should do. But am not sure about the scope of the instances created. If they are global, we have guaranteed non-overlapping of keys.

From the documentation of id

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

May be you should try other approaches, which guarantees keys uniqueness for your collection and also have a uniform distribution. In our implementation, we will generate some hashcode (md5 or sha1) from instance identification data.



Answered By - arunk2
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,207,321

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing