Skip to content

Add queryset cache #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "django-user-defined-fields"
version = "0.0.14"
version = "0.0.15"
description = "A Django app for user defined fields"
authors = ["Aidan Lister <aidan@uptickhq.com>"]
license = "MIT"
Expand Down
24 changes: 19 additions & 5 deletions userdefinedfields/fields.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from functools import partialmethod

from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.core.exceptions import FieldDoesNotExist
from django.db.models import JSONField
from django.db.models.fields.related import ForeignKey
Expand All @@ -14,13 +15,26 @@ def __init__(self, *args, **kwargs):
kwargs["blank"] = True
super().__init__(*args, **kwargs)

def _get_EXTRAFIELD_fieldlist(self, obj, field):
ct = ContentType.objects.get_for_model(obj)
def _get_EXTRAFIELD_fieldlist(self, obj, field, use_cache=False):

# grab the relevant extrafields for this content type
relevant_fields = ExtraField.objects.filter(content_type=ct).prefetch_related(
"displaycondition_set"
)
# Cache the results, if using the cache
if use_cache:
cache_key = f"django-extra-fields-{hash(type(obj))}"
relevant_fields = cache.get(cache_key)
else:
relevant_fields = None

if not relevant_fields:
ct = ContentType.objects.get_for_model(obj)
relevant_fields = (
ExtraField.objects.filter(content_type=ct)
.prefetch_related("displaycondition_set")
.all()
)

if use_cache:
cache.set(cache_key, relevant_fields, 30)

# include only the fields that aren't rejected by their display conditions.
filtered_fields = []
Expand Down