10👍
You can decide between several solutions:
-
Generic relation pre-fetching, you can use this snippet like this example app.
-
Identity map/caching, use the content type and object id to make the key to cache the model, here is an example you can take the code inside
__getstate__
and__setstate__
and make a template tag, this is the fastest solution you can find -
Fetching relations directly, at some point you will probably need one of the solutions detailed in this article about generic relation performance later when you work with foreign keys.
-
Use JonhyCache, JohnyCache is a caching framework for querysets which works with the django caching abstraction. I did not personally try it yet, as the three solutions were sufficient in my projects.
-
Cache the template fragment, less hacky, it looks like official way to deal with this kind of issue that spawns a lot of queries, and when the user changes his favorites you could invalidate the cached version.
Note that select_related() doesn’t work on generic relations. This is because the related object can be in any table so it’s impossible to make proper joins in pure sql. Generic relations are a feature from Django, not from MySQL.
2👍
Try using the select_related queryset method.
Something like this should do the trick:
item = Favorite.objects.favorites_for_user(user=request.user).select_related('content_type', 'content_object')
EDIT: jpic has rightly pointed out that select_related won’t work for ‘content_object’ because it’s a generic foreign key. Unfortunately there’s no nice built in way to handle this, and there won’t be until Django 1.4 rolls around. In the meantime, check out this SO question for some pointers. jpic has also posted some good solutions in his answer.
- [Django]-How to dynamically make an existing non-abstract django model, abstract?
- [Django]-To what framework is it worth to switch from django
- [Django]-MongoDB storage along with MySQL XPath features
- [Django]-Passing a Django database pk id to Dash app