| 1 |
from django import forms |
| 2 |
from django.db import models |
| 3 |
from django.db.models import functions |
| 4 |
from polymorphic.models import PolymorphicModel, PolymorphicTypeInvalid |
| 5 |
from polymorphic.tests.models import ( |
| 6 |
Bottom, |
| 7 |
Middle, |
| 8 |
Top, |
| 9 |
Team, |
| 10 |
UserProfile, |
| 11 |
Model2A, |
| 12 |
Model2B, |
| 13 |
Regression295Parent, |
| 14 |
Regression295Related, |
| 15 |
RelationBase, |
| 16 |
RelationA, |
| 17 |
RelationB, |
| 18 |
SpecialBook, |
| 19 |
Book, |
| 20 |
) |
| 21 |
from django.test import TestCase |
| 22 |
from django.contrib.contenttypes.models import ContentType |
| 23 |
from polymorphic.formsets import polymorphic_modelformset_factory, PolymorphicFormSetChild |
| 24 |
|
| 25 |
|
| 26 |
class RegressionTests(TestCase): |
| 27 |
def test_for_query_result_incomplete_with_inheritance(self): |
| 28 |
"""https://github.com/bconstantin/django_polymorphic/issues/15""" |
| 29 |
|
| 30 |
top = Top() |
| 31 |
top.save() |
| 32 |
middle = Middle() |
| 33 |
middle.save() |
| 34 |
bottom = Bottom() |
| 35 |
bottom.save() |
| 36 |
|
| 37 |
expected_queryset = [top, middle, bottom] |
| 38 |
self.assertQuerySetEqual( |
| 39 |
Top.objects.order_by("pk"), |
| 40 |
[repr(r) for r in expected_queryset], |
| 41 |
transform=repr, |
| 42 |
) |
| 43 |
|
| 44 |
expected_queryset = [middle, bottom] |
| 45 |
self.assertQuerySetEqual( |
| 46 |
Middle.objects.order_by("pk"), |
| 47 |
[repr(r) for r in expected_queryset], |
| 48 |
transform=repr, |
| 49 |
) |
| 50 |
|
| 51 |
expected_queryset = [bottom] |
| 52 |
self.assertQuerySetEqual( |
| 53 |
Bottom.objects.order_by("pk"), |
| 54 |
[repr(r) for r in expected_queryset], |
| 55 |
transform=repr, |
| 56 |
) |
| 57 |
|
| 58 |
def test_pr_254(self): |
| 59 |
user_a = UserProfile.objects.create(name="a") |
| 60 |
user_b = UserProfile.objects.create(name="b") |
| 61 |
user_c = UserProfile.objects.create(name="c") |
| 62 |
|
| 63 |
team1 = Team.objects.create(team_name="team1") |
| 64 |
team1.user_profiles.add(user_a, user_b, user_c) |
| 65 |
team1.save() |
| 66 |
|
| 67 |
team2 = Team.objects.create(team_name="team2") |
| 68 |
team2.user_profiles.add(user_c) |
| 69 |
team2.save() |
| 70 |
|
| 71 |
# without prefetch_related, the test passes |
| 72 |
my_teams = ( |
| 73 |
Team.objects.filter(user_profiles=user_c) |
| 74 |
.order_by("team_name") |
| 75 |
.prefetch_related("user_profiles") |
| 76 |
.distinct() |
| 77 |
) |
| 78 |
|
| 79 |
self.assertEqual(len(my_teams[0].user_profiles.all()), 3) |
| 80 |
|
| 81 |
self.assertEqual(len(my_teams[1].user_profiles.all()), 1) |
| 82 |
|
| 83 |
self.assertEqual(len(my_teams[0].user_profiles.all()), 3) |
| 84 |
self.assertEqual(len(my_teams[1].user_profiles.all()), 1) |
| 85 |
|
| 86 |
# without this "for" loop, the test passes |
| 87 |
for _ in my_teams: |
| 88 |
pass |
| 89 |
|
| 90 |
# This time, test fails. PR 254 claim |
| 91 |
# with sqlite: 4 != 3 |
| 92 |
# with postgresql: 2 != 3 |
| 93 |
self.assertEqual(len(my_teams[0].user_profiles.all()), 3) |
| 94 |
self.assertEqual(len(my_teams[1].user_profiles.all()), 1) |
| 95 |
|
| 96 |
def test_alias_queryset(self): |
| 97 |
""" |
| 98 |
Test that .alias() works works correctly with polymorphic querysets. |
| 99 |
It should not raise AttributeError, and the aliased field should NOT be present on the instance. |
| 100 |
""" |
| 101 |
Model2B.objects.create(field1="val1", field2="val2") |
| 102 |
|
| 103 |
# Scenario 1: .alias() only |
| 104 |
# Should not crash, and 'lower_field1' should NOT be an attribute |
| 105 |
qs = Model2A.objects.alias(lower_field1=functions.Lower("field1")) |
| 106 |
results = list(qs) |
| 107 |
self.assertEqual(len(results), 1) |
| 108 |
self.assertIsInstance(results[0], Model2B) |
| 109 |
self.assertFalse(hasattr(results[0], "lower_field1")) |
| 110 |
|
| 111 |
# Scenario 2: .annotate() |
| 112 |
# Should work, and 'upper_field1' SHOULD be an attribute |
| 113 |
qs = Model2A.objects.annotate(upper_field1=functions.Upper("field1")) |
| 114 |
results = list(qs) |
| 115 |
self.assertEqual(len(results), 1) |
| 116 |
self.assertTrue(hasattr(results[0], "upper_field1")) |
| 117 |
self.assertEqual(results[0].upper_field1, "VAL1") |
| 118 |
|
| 119 |
# Scenario 3: Mixed alias() and annotate() |
| 120 |
qs = Model2A.objects.alias(alias_val=functions.Lower("field1")).annotate( |
| 121 |
anno_val=functions.Upper("field1") |
| 122 |
) |
| 123 |
results = list(qs) |
| 124 |
self.assertEqual(len(results), 1) |
| 125 |
self.assertFalse(hasattr(results[0], "alias_val")) |
| 126 |
self.assertTrue(hasattr(results[0], "anno_val")) |
| 127 |
self.assertEqual(results[0].anno_val, "VAL1") |
| 128 |
|
| 129 |
def test_alias_advanced(self): |
| 130 |
""" |
| 131 |
Test .alias() interactions with filter, order_by, only, and defer. |
| 132 |
""" |
| 133 |
obj1 = Model2B.objects.create(field1="Alpha", field2="One") |
| 134 |
obj2 = Model2B.objects.create(field1="Beta", field2="Two") |
| 135 |
obj3 = Model2B.objects.create(field1="Gamma", field2="Three") |
| 136 |
|
| 137 |
# 1. Filter by alias |
| 138 |
qs = Model2A.objects.alias(lower_f1=functions.Lower("field1")).filter(lower_f1="beta") |
| 139 |
self.assertEqual(qs.count(), 1) |
| 140 |
self.assertEqual(qs[0], obj2) |
| 141 |
self.assertFalse(hasattr(qs[0], "lower_f1")) |
| 142 |
|
| 143 |
# 2. Order by alias |
| 144 |
qs = Model2A.objects.alias(len_f2=functions.Length("model2b__field2")).order_by("len_f2") |
| 145 |
# Lengths: One=3, Two=3, Three=5. (Ordering of equal values is DB dep, but logic holds) |
| 146 |
results = list(qs) |
| 147 |
self.assertEqual(len(results), 3) |
| 148 |
self.assertFalse(hasattr(results[0], "len_f2")) |
| 149 |
|
| 150 |
# 3. Alias + Only |
| 151 |
qs = Model2A.objects.alias(lower_f1=functions.Lower("field1")).only("field1") |
| 152 |
# Should not crash |
| 153 |
results = list(qs) |
| 154 |
self.assertEqual(len(results), 3) |
| 155 |
# Verify deferral logic didn't break |
| 156 |
# accessing field1 should not trigger refresh (hard to test without internals, but basic access works) |
| 157 |
self.assertEqual(results[0].field1, "Alpha") |
| 158 |
|
| 159 |
# 4. Alias + Defer |
| 160 |
qs = Model2A.objects.alias(lower_f1=functions.Lower("field1")).defer("field1") |
| 161 |
results = list(qs) |
| 162 |
self.assertEqual(len(results), 3) |
| 163 |
# accessing field1 should trigger refresh |
| 164 |
self.assertEqual(results[0].field1, "Alpha") |
| 165 |
|
| 166 |
def test_upcasting_to_sibling_class(self): |
| 167 |
""" |
| 168 |
Test that querying a model that has been upcasted to a sibling |
| 169 |
polymorphic class does not raise a TypeError. |
| 170 |
Reproduces issue #280. |
| 171 |
""" |
| 172 |
# Create a Model2A instance with a specific pk |
| 173 |
Model2A.objects.create(pk=1, field1="original") |
| 174 |
|
| 175 |
# "Upcast" it to a Model2B by creating an object with the same pk. |
| 176 |
# The polymorphic_ctype will now point to Model2B. |
| 177 |
Model2B.objects.create(pk=1, field1="updated", field2="new") |
| 178 |
|
| 179 |
# The original bug raised TypeError. We expect that accessing the |
| 180 |
# queryset should not raise TypeError. It should either be empty, |
| 181 |
# or raise a clean PolymorphicTypeInvalid error. |
| 182 |
try: |
| 183 |
list(Model2A.objects.all()) |
| 184 |
except PolymorphicTypeInvalid: |
| 185 |
pass # This is an acceptable outcome. |
| 186 |
except TypeError as e: |
| 187 |
self.fail(f"Querying for upcasted sibling raised TypeError: {e}") |
| 188 |
|
| 189 |
def test_mixed_inheritance_save_issue_495(self): |
| 190 |
""" |
| 191 |
Test that saving models with mixed polymorphic and non-polymorphic |
| 192 |
inheritance works correctly. This addresses issue #495. |
| 193 |
""" |
| 194 |
from polymorphic.tests.models import NormalExtension, PolyExtension, PolyExtChild |
| 195 |
|
| 196 |
# Create and save NormalExtension |
| 197 |
normal_ext = NormalExtension.objects.create(nb_field=1, ne_field="normal") |
| 198 |
normal_ext.add_to_ne(" extended") |
| 199 |
normal_ext.refresh_from_db() |
| 200 |
self.assertEqual(normal_ext.ne_field, "normal extended") |
| 201 |
normal_ext.add_to_nb(5) |
| 202 |
normal_ext.refresh_from_db() |
| 203 |
self.assertEqual(normal_ext.nb_field, 6) |
| 204 |
|
| 205 |
# Create and save PolyExtension |
| 206 |
poly_ext = PolyExtension.objects.create(nb_field=1, ne_field="normal", poly_ext_field=10) |
| 207 |
poly_ext.add_to_ne(" extended") |
| 208 |
poly_ext.refresh_from_db() |
| 209 |
self.assertEqual(poly_ext.ne_field, "normal extended") |
| 210 |
poly_ext.add_to_ext(5) |
| 211 |
poly_ext.refresh_from_db() |
| 212 |
self.assertEqual(poly_ext.poly_ext_field, 15) |
| 213 |
poly_ext.add_to_nb(5) |
| 214 |
poly_ext.refresh_from_db() |
| 215 |
self.assertEqual(poly_ext.nb_field, 6) |
| 216 |
|
| 217 |
# Create and save PolyExtChild |
| 218 |
poly_child = PolyExtChild.objects.create( |
| 219 |
nb_field=1, ne_field="normal", poly_ext_field=20, poly_child_field="child" |
| 220 |
) |
| 221 |
poly_child.add_to_ne(" extended") |
| 222 |
poly_child.add_to_nb(5) |
| 223 |
poly_child.add_to_ext(10) |
| 224 |
poly_child.add_to_child(" added") |
| 225 |
poly_child.refresh_from_db() |
| 226 |
self.assertEqual(poly_child.nb_field, 6) |
| 227 |
self.assertEqual(poly_child.ne_field, "normal extended") |
| 228 |
self.assertEqual(poly_child.poly_ext_field, 30) |
| 229 |
self.assertEqual(poly_child.poly_child_field, "child added") |
| 230 |
|
| 231 |
poly_child.override_add_to_ne(" overridden") |
| 232 |
poly_child.override_add_to_ext(5) |
| 233 |
poly_child.refresh_from_db() |
| 234 |
self.assertEqual(poly_child.ne_field, "normal extended OVERRIDDEN") |
| 235 |
self.assertEqual(poly_child.poly_ext_field, 40) |
| 236 |
|
| 237 |
def test_create_or_update(self): |
| 238 |
""" |
| 239 |
https://github.com/jazzband/django-polymorphic/issues/494 |
| 240 |
""" |
| 241 |
from polymorphic.tests.models import Model2B, Model2C |
| 242 |
|
| 243 |
obj, created = Model2B.objects.update_or_create( |
| 244 |
field1="value1", defaults={"field2": "value2"} |
| 245 |
) |
| 246 |
self.assertTrue(created) |
| 247 |
self.assertEqual(obj.field1, "value1") |
| 248 |
self.assertEqual(obj.field2, "value2") |
| 249 |
|
| 250 |
obj2, created = Model2B.objects.update_or_create( |
| 251 |
field1="value1", defaults={"field2": "new_value2"} |
| 252 |
) |
| 253 |
self.assertFalse(created) |
| 254 |
self.assertEqual(obj2.pk, obj.pk) |
| 255 |
self.assertEqual(obj2.field1, "value1") |
| 256 |
self.assertEqual(obj2.field2, "new_value2") |
| 257 |
|
| 258 |
self.assertEqual(Model2B.objects.count(), 1) |
| 259 |
|
| 260 |
obj3, created = Model2C.objects.update_or_create( |
| 261 |
field1="value1", defaults={"field2": "new_value3", "field3": "value3"} |
| 262 |
) |
| 263 |
|
| 264 |
self.assertTrue(created) |
| 265 |
self.assertEqual(Model2B.objects.count(), 2) |
| 266 |
self.assertEqual(Model2C.objects.count(), 1) |
| 267 |
self.assertEqual(obj3, Model2B.objects.order_by("pk").last()) |
| 268 |
|
| 269 |
def test_double_underscore_in_related_name(self): |
| 270 |
""" |
| 271 |
Test filtering on a related field when the relation name itself contains '__'. |
| 272 |
This reproduces the issue in #295, where 'my__relation___real_field' was |
| 273 |
being incorrectly parsed as a polymorphic lookup. |
| 274 |
""" |
| 275 |
|
| 276 |
related = Regression295Related.objects.create(_real_field="test_value") |
| 277 |
Regression295Parent.objects.create(related_object=related) |
| 278 |
|
| 279 |
# The following filter would be translated to 'related_object___real_field' |
| 280 |
# by Django's query machinery. |
| 281 |
qs = Regression295Parent.objects.filter(related_object___real_field="test_value") |
| 282 |
self.assertEqual(qs.count(), 1) |
| 283 |
|
| 284 |
def test_issue_252_abstract_base_class(self): |
| 285 |
""" |
| 286 |
Test that polymorphic models inheriting from both an abstract model |
| 287 |
and PolymorphicModel can be created and saved without IndexError. |
| 288 |
|
| 289 |
This reproduces issue #252: |
| 290 |
https://github.com/jazzband/django-polymorphic/issues/252 |
| 291 |
|
| 292 |
The issue reported an IndexError when trying to create an Event object |
| 293 |
that inherited from both an abstract model (AbstractDateInfo) and |
| 294 |
PolymorphicModel. The error occurred in Django's query_utils.py when |
| 295 |
accessing polymorphic_ctype_id. |
| 296 |
|
| 297 |
We use RelationBase which inherits from RelationAbstractModel (abstract) |
| 298 |
and PolymorphicModel, demonstrating the same pattern. |
| 299 |
""" |
| 300 |
# Test creating base polymorphic model with abstract parent |
| 301 |
# RelationBase inherits from RelationAbstractModel (abstract) and PolymorphicModel |
| 302 |
base = RelationBase(field_base="test_base") |
| 303 |
# This should not raise IndexError |
| 304 |
base.save() |
| 305 |
|
| 306 |
# Verify the object was saved correctly |
| 307 |
self.assertIsNotNone(base.pk) |
| 308 |
self.assertEqual(base.field_base, "test_base") |
| 309 |
self.assertIsNotNone(base.polymorphic_ctype_id) |
| 310 |
|
| 311 |
# Test creating child models |
| 312 |
relation_a = RelationA.objects.create(field_base="base_a", field_a="field_a_value") |
| 313 |
self.assertIsNotNone(relation_a.pk) |
| 314 |
self.assertEqual(relation_a.field_a, "field_a_value") |
| 315 |
|
| 316 |
relation_b = RelationB.objects.create(field_base="base_b", field_b="field_b_value") |
| 317 |
self.assertIsNotNone(relation_b.pk) |
| 318 |
self.assertEqual(relation_b.field_b, "field_b_value") |
| 319 |
|
| 320 |
# Test querying polymorphic objects |
| 321 |
relations = RelationBase.objects.all().order_by("pk") |
| 322 |
self.assertEqual(relations.count(), 3) |
| 323 |
|
| 324 |
# Verify polymorphic behavior - objects should be returned as their actual types |
| 325 |
self.assertIsInstance(relations[0], RelationBase) |
| 326 |
self.assertIsInstance(relations[1], RelationA) |
| 327 |
self.assertIsInstance(relations[2], RelationB) |
| 328 |
|
| 329 |
|
| 330 |
class SpecialBookForm(forms.ModelForm): |
| 331 |
class Meta: |
| 332 |
model = SpecialBook |
| 333 |
exclude = ("author",) |
| 334 |
|
| 335 |
|
| 336 |
class TestFormsetExclude(TestCase): |
| 337 |
def test_formset_child_respects_exclude(self): |
| 338 |
SpecialBookFormSet = polymorphic_modelformset_factory( |
| 339 |
Book, |
| 340 |
fields=[], |
| 341 |
formset_children=(PolymorphicFormSetChild(SpecialBook, form=SpecialBookForm),), |
| 342 |
) |
| 343 |
formset = SpecialBookFormSet(queryset=SpecialBook.objects.none()) |
| 344 |
self.assertNotIn("author", formset.forms[0].fields) |
| 345 |
|
| 346 |
def test_formset_initial_with_contenttype_instance(self): |
| 347 |
"""Test that polymorphic_ctype can be set as ContentType instance in initial data (issue #549)""" |
| 348 |
from django.contrib.contenttypes.models import ContentType |
| 349 |
|
| 350 |
ct = ContentType.objects.get_for_model(SpecialBook, for_concrete_model=False) |
| 351 |
|
| 352 |
SpecialBookFormSet = polymorphic_modelformset_factory( |
| 353 |
Book, |
| 354 |
fields="__all__", |
| 355 |
formset_children=(PolymorphicFormSetChild(SpecialBook, form=SpecialBookForm),), |
| 356 |
) |
| 357 |
|
| 358 |
# Set initial data with ContentType instance (as users do in issue #549) |
| 359 |
formset = SpecialBookFormSet( |
| 360 |
queryset=SpecialBook.objects.none(), |
| 361 |
initial=[{"polymorphic_ctype": ct}], |
| 362 |
) |
| 363 |
|
| 364 |
# Should not raise an error when creating the formset |
| 365 |
form = formset.forms[0] |
| 366 |
|
| 367 |
# Verify the polymorphic_ctype field is properly set up with the ID |
| 368 |
self.assertIn("polymorphic_ctype", form.fields) |
| 369 |
|
| 370 |
# The critical assertion: the field's initial value should be the ID (int), |
| 371 |
# not the ContentType instance. This proves the normalization worked. |
| 372 |
self.assertEqual(form.fields["polymorphic_ctype"].initial, ct.pk) |
| 373 |
self.assertIsInstance(form.fields["polymorphic_ctype"].initial, int) |
| 374 |
|
| 375 |
def test_formset_with_none_instance(self): |
| 376 |
"""Test that formset handles None instance without AttributeError (issue #363). |
| 377 |
|
| 378 |
This occurs when a bound formset has a pk that doesn't exist in the queryset, |
| 379 |
causing Django's _existing_object to return None. The polymorphic formset |
| 380 |
must handle this gracefully instead of calling get_real_instance_class() on None. |
| 381 |
""" |
| 382 |
from django.contrib.contenttypes.models import ContentType |
| 383 |
|
| 384 |
ct = ContentType.objects.get_for_model(SpecialBook, for_concrete_model=False) |
| 385 |
|
| 386 |
SpecialBookFormSet = polymorphic_modelformset_factory( |
| 387 |
Book, |
| 388 |
fields="__all__", |
| 389 |
formset_children=(PolymorphicFormSetChild(SpecialBook, form=SpecialBookForm),), |
| 390 |
) |
| 391 |
|
| 392 |
# Simulate the scenario where _existing_object returns None: |
| 393 |
# - Bound formset with data |
| 394 |
# - Claims to have an initial form (INITIAL_FORMS > 0) |
| 395 |
# - But the pk doesn't exist in queryset, so _existing_object returns None |
| 396 |
data = { |
| 397 |
"form-TOTAL_FORMS": "1", |
| 398 |
"form-INITIAL_FORMS": "1", |
| 399 |
"form-MIN_NUM_FORMS": "0", |
| 400 |
"form-MAX_NUM_FORMS": "1000", |
| 401 |
"form-0-id": "99999", # Non-existent pk - _existing_object will return None |
| 402 |
"form-0-polymorphic_ctype": str(ct.pk), |
| 403 |
} |
| 404 |
|
| 405 |
formset = SpecialBookFormSet(data=data, queryset=SpecialBook.objects.none()) |
| 406 |
|
| 407 |
# This should not raise AttributeError when instance is None |
| 408 |
forms = formset.forms |
| 409 |
self.assertEqual(len(forms), 1) |
| 410 |
self.assertIn("polymorphic_ctype", forms[0].fields) |
| 411 |
|
| 412 |
def test_combined_formset_behaviors(self): |
| 413 |
# 1. __init__ exclude handling |
| 414 |
child_none = PolymorphicFormSetChild(Book, form=SpecialBookForm, exclude=None) |
| 415 |
self.assertEqual(child_none.exclude, ()) |
| 416 |
|
| 417 |
child_list = PolymorphicFormSetChild(Book, form=SpecialBookForm, exclude=["author"]) |
| 418 |
self.assertIn("author", child_list.exclude) |
| 419 |
|
| 420 |
# 2. get_form exclude merging |
| 421 |
form = child_list.get_form(extra_exclude=["field1"]) |
| 422 |
self.assertIn("author", form._meta.exclude) |
| 423 |
self.assertIn("field1", form._meta.exclude) |
| 424 |
|
| 425 |
form_meta_default = child_none.get_form() |
| 426 |
self.assertIn("author", form_meta_default._meta.exclude) |
| 427 |
|
| 428 |
# 3. polymorphic_ctype normalization |
| 429 |
ct = ContentType.objects.get_for_model(SpecialBook, for_concrete_model=False) |
| 430 |
SpecialBookFormSet = polymorphic_modelformset_factory( |
| 431 |
Book, |
| 432 |
fields="__all__", |
| 433 |
formset_children=(PolymorphicFormSetChild(SpecialBook, form=SpecialBookForm),), |
| 434 |
) |
| 435 |
formset = SpecialBookFormSet( |
| 436 |
queryset=SpecialBook.objects.none(), |
| 437 |
initial=[{"polymorphic_ctype": ct}], |
| 438 |
) |
| 439 |
# The formset should normalize the ContentType instance to its ID |
| 440 |
form_ct = formset.forms[0] |
| 441 |
self.assertIsInstance(form_ct.initial["polymorphic_ctype"], int) |
| 442 |
self.assertEqual(form_ct.initial["polymorphic_ctype"], ct.pk) |