Search code examples
djangodjango-cache

how can I cache get_or_create tuple - django


how can I cache the obj (not the created)

obj, created = MyModel.objects.get_or_create(id=someid)

I cannot do:

cached_tuple = cache.set('cachekey', obj, created, 600)

any ideas?


Solution

  • Do you need the created boolean cached? You can cache both separately:

    cache.set('cachekey_obj', obj, 600)
    cache.set('cachekey_created', created, 600)
    

    But I'm not sure what you'd want with that. You could also try:

    tpl = MyModel.objects.get_or_create(id=someid)
    cache.set('cachekey', tpl, 600)
    

    and then this should work, but I haven't checked right now:

    obj, created = cache.get('cachekey')