Coverage for apis_core/relations/models.py: 83%
102 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-23 06:59 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-23 06:59 +0000
1import functools
2import logging
3from typing import Optional
5from django.contrib.contenttypes.fields import GenericForeignKey
6from django.contrib.contenttypes.models import ContentType
7from django.core.exceptions import ValidationError
8from django.db import models
9from django.db.models import Case, When
10from django.db.models.base import ModelBase
11from django.http.request import HttpRequest
12from django.utils.translation import gettext_lazy as _
13from model_utils.managers import InheritanceManager
15from apis_core.generic.abc import GenericModel
17logger = logging.getLogger(__name__)
20class RelationManager(InheritanceManager):
21 def create_between_instances(self, subj, obj, *args, **kwargs):
22 subj_object_id = subj.pk
23 subj_content_type = ContentType.objects.get_for_model(subj)
24 obj_object_id = obj.pk
25 obj_content_type = ContentType.objects.get_for_model(obj)
26 rel = self.create(
27 subj_object_id=subj_object_id,
28 subj_content_type=subj_content_type,
29 obj_object_id=obj_object_id,
30 obj_content_type=obj_content_type,
31 )
32 logger.debug("Created relation %s between %s and %s", rel.name(), subj, obj)
33 return rel
35 def to_content_type_with_targets(self, content_type):
36 """
37 Return the queryset annotated with the target content type
38 and object id, based on the content_type that is passed.
39 """
40 return self.annotate(
41 target_content_type=Case(
42 When(subj_content_type=content_type, then="obj_content_type"),
43 default="subj_content_type",
44 ),
45 target_id=Case(
46 When(subj_content_type=content_type, then="obj_object_id"),
47 default="subj_object_id",
48 ),
49 )
52# This ModelBase is simply there to check if the needed attributes
53# are set in the Relation child classes.
54class RelationModelBase(ModelBase):
55 def __new__(metacls, name, bases, attrs):
56 if name == "Relation":
57 return super().__new__(metacls, name, bases, attrs)
58 else:
59 new_class = super().__new__(metacls, name, bases, attrs)
60 if not (new_class._meta.abstract or new_class._meta.proxy):
61 if not hasattr(new_class, "subj_model"):
62 raise ValueError(
63 "%s inherits from Relation and must therefore specify subj_model"
64 % name
65 )
66 if not hasattr(new_class, "obj_model"):
67 raise ValueError(
68 "%s inherits from Relation and must therefore specify obj_model"
69 % name
70 )
72 # `subj_model` or `obj_model` being a list was supported in an earlier
73 # version of apis, but it is not anymore
74 if isinstance(getattr(new_class, "subj_model", None), list):
75 raise ValueError("%s.subj_model must not be a list" % name)
76 if isinstance(getattr(new_class, "obj_model", None), list):
77 raise ValueError("%s.obj_model mut not be a list" % name)
79 if not new_class._meta.ordering:
80 logger.warning(
81 f"{name} inherits from Relation but does not specify 'ordering' in its Meta class. "
82 "Empty ordering could result in inconsitent results with pagination. "
83 "Set a ordering or inherit the Meta class from Relation.",
84 )
86 return new_class
89@functools.cache
90def get_by_natural_key(natural_key: str):
91 app_label, name = natural_key.lower().split(".")
92 return ContentType.objects.get_by_natural_key(app_label, name).model_class()
95class Relation(GenericModel, models.Model, metaclass=RelationModelBase):
96 class Config(GenericModel.Config):
97 overview_section = _("Relations")
98 search_initial = True
100 subj_content_type = models.ForeignKey(
101 ContentType, on_delete=models.CASCADE, related_name="relation_subj_set"
102 )
103 subj_object_id = models.PositiveIntegerField(null=True)
104 subj = GenericForeignKey("subj_content_type", "subj_object_id")
105 obj_content_type = models.ForeignKey(
106 ContentType, on_delete=models.CASCADE, related_name="relation_obj_set"
107 )
108 obj_object_id = models.PositiveIntegerField(null=True)
109 obj = GenericForeignKey("obj_content_type", "obj_object_id")
111 objects = RelationManager()
113 class Meta:
114 indexes = [
115 models.Index(
116 fields=["subj_content_type"], name="relations_r_subj_content_type"
117 ),
118 models.Index(fields=["subj_object_id"], name="relations_r_subj_object_id"),
119 models.Index(
120 fields=["obj_content_type"], name="relations_r_obj_content_type"
121 ),
122 models.Index(fields=["obj_object_id"], name="relations_r_obj_object_id"),
123 models.Index(
124 fields=["subj_content_type", "subj_object_id"],
125 name="relations_r_subj_c_t_o_i",
126 ),
127 models.Index(
128 fields=["obj_content_type", "obj_object_id"],
129 name="relations_r_obj_c_t_o_i",
130 ),
131 ]
133 def save(self, *args, **kwargs):
134 subj_model = getattr(self, "subj_model", None)
135 if subj_model and self.subj_content_type.model_class() is not subj_model:
136 raise ValidationError(f"{self.subj} is not of type {subj_model}")
137 obj_model = getattr(self, "obj_model", None)
138 if obj_model and self.obj_content_type.model_class() is not obj_model:
139 raise ValidationError(f"{self.obj} is not of type {obj_model}")
140 super().save(*args, **kwargs)
142 @property
143 def subj_to_obj_text(self) -> str:
144 if hasattr(self, "name"):
145 return f"{self.subj} {self.name()} {self.obj}"
146 return f"{self.subj} relation to {self.obj}"
148 @property
149 def obj_to_subj_text(self) -> str:
150 if hasattr(self, "reverse_name"):
151 return f"{self.obj} {self.reverse_name()} {self.subj}"
152 return f"{self.obj} relation to {self.subj}"
154 def __str__(self):
155 return self.subj_to_obj_text
157 @classmethod
158 def subj_model_type(cls):
159 model = cls.subj_model
160 return get_by_natural_key(model) if isinstance(model, str) else model
162 @classmethod
163 def obj_model_type(cls):
164 model = cls.obj_model
165 return get_by_natural_key(model) if isinstance(model, str) else model
167 @classmethod
168 def name(cls) -> str:
169 return cls._meta.verbose_name
171 @classmethod
172 def reverse_name(cls) -> str:
173 return cls._meta.verbose_name + " reverse"
175 @classmethod
176 def name_and_reverse_name(cls) -> str:
177 """
178 Return a string with both the name and the reverse name.
180 If they are identical, return only the name.
181 """
182 if cls.name() != cls.reverse_name():
183 return f"{cls.name()} - {cls.reverse_name()}"
184 return cls.name()
186 def get_update_success_url(self, request: Optional[HttpRequest] = None):
187 if request and request.GET.get("redirect", False):
188 return super().get_update_success_url(request)
189 return self.get_absolute_url()