On Sep 30, 12:46 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi guys,
>
> I was wondering if somebody could help me with deserialization.
>
> I'm currently trying to cache the result of a database query using a
> JSON serializer in (what I assume to be) the standard fashion:
>
> -----------
> def cache_query(id):
> cache_key = "cache_key_" % id
> item = cache.get(cache_key)
>
> if item is None:
> item_obj = Item.objects.filter(id=id)
Realize that item_obj here is really a QuerySet because filter()
always returns a QuerySet even if this query matches just one row.
Since you're caching only one model instance, you could simply replace
the above with:
item_obj = Item.objects.get(id=id)
Then when you deserialized this cached item_obj, it won't call the DB.
> item = serializers.serialize("json", item_obj,
> ensure_ascii=False)
> cache.set(cache_key, item, 30) # I've just chosen a random
> number for seconds here
> item_deserial = list(serializers.deserialize("json", item))
> [0].object
>
> return item_deserial
> ------------
>
> It seems like the deserializer is talking to the database in order to
> reconstruct the queryset. I may be wrong on this, but commenting out
> the deserializer line reduces the number of queries by the amount I'd
> expect if it was not talking to the database. It's obviously quite
> helpful reconstructing a queryset (as you can follow foreign key
> relationships etc), but is there anyway to purposely prevent it from
> recontacting the database? Is it even contacting the database?
>
> I'd really like to minimise the number of queries and I don't need the
> full flexibility of a Queryset, a dictionary of the values would be
> more than adequate for what I'm doing, which I could extract from the
> serialized values (after a bit of eval/str fun!).
You can use the values() method on a QuerySet to get dictionaries of
rows. You can even choose which fields you are interested in. Then,
run a list() call on such a queryset and cache that result.
See documentation of QuerySet.values() here:
http://docs.djangoproject.com/en/dev//ref/models/querysets/#values-fields
>
> If somebody could point out any obvious errors with my code, I'd be
> really grateful! I'm very new the caching, so any pointers would be
> great.
>
-RD
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---