18👍
I’d like to quote some words from David Cramer: developer of Disqus, Django commiter
Generic relations are fine. They are not slow, just more difficult to manage in your code base.
I saw many people tell others don’t use generic relations because it’s slow, but never tell how it’s slow.
18👍
Avoid Django’s GenericForeignKey has a good and thorough description of the database design antipatterns involved in generic foreign keys (or “polymorphic associations,” as they call them in rails-speak).
As for performance, it takes 3 database queries every time you want to retrieve the related GenericForeignKey resource from your model:
- SELECT object_id_field, object_id from myapp_a WHERE id=1;
- SELECT app_label, model FROM django_content_type WHERE id=A.object_type_field;
- In application code, compute table name
model + _ + app_label
- In application code, compute table name
- SELECT A.object_id_field FROM
TABLE_NAME
;
When people say that Generic Foreign Keys have a performance penalty, they are referencing this query overhead.
There are only a very narrow set of circumstances under which you really want to use generic foreign keys. The above-linked article discusses those, as well.
- Installed Virtualenv and activating virtualenv doesn't work
- Django – how to filter out GET static and media messages with logging?
- Get_list_or_404 ordering in django
- Django testing: Got an error creating the test database: database "database_name" already exists
3👍
Add an index_together Meta option to your model:
class Meta:
index_together = [('cprofile_id', 'cprofile_type')]
- "Apps aren't loaded yet" when trying to run pytest-django
- Example when request.POST contain query string in django