Skip to content

Commit

Permalink
Merge pull request #1520 from laws-africa/speed-rels
Browse files Browse the repository at this point in the history
smarter relationship loading to avoid N+1
  • Loading branch information
longhotsummer authored Sep 8, 2023
2 parents ab6b9b6 + ef3a994 commit 8461b6b
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 22 deletions.
19 changes: 0 additions & 19 deletions peachjam/models/core_document_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import models
from django.utils.functional import cached_property
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from docpipe.pipeline import PipelineContext
Expand Down Expand Up @@ -551,24 +550,6 @@ def save(self, *args, **kwargs):
# apply labels
self.apply_labels()

@cached_property
def relationships_as_subject(self):
"""Returns a list of relationships where this work is the subject."""
from peachjam.models import Relationship

return Relationship.for_subject_document(self).prefetch_related(
"subject_work", "subject_work__documents"
)

@cached_property
def relationships_as_object(self):
"""Returns a list of relationships where this work is the subject."""
from peachjam.models import Relationship

return Relationship.for_object_document(self).prefetch_related(
"object_work", "object_work__documents"
)

def extract_citations(self):
"""Run citation extraction on this document. If the document has content_html,
extraction will be run on that. Otherwise, if the document as a PDF source file,
Expand Down
10 changes: 7 additions & 3 deletions peachjam/views/generic_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,17 @@ def fetch_docs(self, works):

def add_relationships(self, context):
context["relationships_as_subject"] = rels_as_subject = list(
context["document"].relationships_as_subject.all()
Relationship.for_subject_document(context["document"])
.prefetch_related("subject_work")
.select_related("predicate")
)
context["relationships_as_object"] = rels_as_object = list(
context["document"].relationships_as_object.all()
Relationship.for_object_document(context["document"])
.prefetch_related("object_work")
.select_related("predicate")
)
context["relationship_limit"] = 4
context["n_relationships"] = len(rels_as_subject) + len(rels_as_object)
context["relationship_limit"] = 4

def add_provision_relationships(self, context):
rels = [
Expand Down

0 comments on commit 8461b6b

Please sign in to comment.