Debian Codegraph @

modeltranslation/tests/models.py

raw symbols SCIP
1 # mypy: disable-error-code="django-manager-missing"
2 from __future__ import annotations
3
4 from django.contrib.auth.models import Permission
5 from django.core import validators
6 from django.db import models
7 from django.utils.translation import gettext_lazy
8
9 from modeltranslation.manager import MultilingualManager
10 from typing import Any
11
12
13 class TestModel(models.Model):
14 title = models.CharField(gettext_lazy("title"), max_length=255)
15 text = models.TextField(blank=True, null=True)
16 url = models.URLField(blank=True, null=True)
17 email = models.EmailField(blank=True, null=True)
18 dynamic_default = models.CharField(default=gettext_lazy("password"), max_length=255)
19
20
21 class UniqueNullableModel(models.Model):
22 title = models.CharField(null=True, unique=True, max_length=255)
23
24
25 class CustomUniqueConstraint(models.UniqueConstraint):
26 pass
27
28
29 class ModelWithConstraint(models.Model):
30 title1 = models.CharField(max_length=255)
31 title2 = models.CharField(max_length=255)
32 title3 = models.CharField(max_length=255)
33 title4 = models.CharField(max_length=255)
34 sub_title1 = models.CharField(max_length=255)
35 sub_title2 = models.CharField(max_length=255)
36 email = models.EmailField(blank=True, null=True)
37
38 class Meta:
39 unique_together = (("title1", "sub_title1"),)
40 constraints = [
41 models.UniqueConstraint(
42 fields=["title2"],
43 name="unique_sfield",
44 ),
45 models.UniqueConstraint(
46 fields=["title3", "sub_title2"],
47 name="unique_mfields",
48 ),
49 models.UniqueConstraint(
50 fields=["title3", "email"],
51 name="unique_partfield",
52 ),
53 CustomUniqueConstraint(
54 fields=["title4", "email"],
55 name="unique_custom",
56 ),
57 ]
58
59
60 class CustomIndex(models.Index):
61 pass
62
63
64 class ModelWithIndex(models.Model):
65 title = models.CharField(max_length=255)
66 sub_title = models.CharField(max_length=255)
67 email = models.EmailField(blank=True, null=True)
68
69 class Meta:
70 indexes = [
71 models.Index(fields=["title"], name="idx_title"),
72 models.Index(fields=["title", "sub_title"], name="idx_title_sub_title"),
73 models.Index(fields=["sub_title"]),
74 models.Index(fields=["email"], name="idx_email"),
75 CustomIndex(fields=["title", "email"], name="idx_custom"),
76 ]
77
78
79 # ######### Proxy model testing
80
81
82 class ProxyTestModel(TestModel):
83 class Meta:
84 proxy = True
85
86 def get_title(self):
87 return self.title
88
89
90 # ######### Fallback values testing
91
92
93 class FallbackModel(models.Model):
94 title = models.CharField(gettext_lazy("title"), max_length=255)
95 text = models.TextField(blank=True, null=True)
96 url = models.URLField(blank=True, null=True)
97 email = models.EmailField(blank=True, null=True)
98 description = models.CharField(max_length=255, null=True)
99
100
101 class FallbackModel2(models.Model):
102 title = models.CharField(gettext_lazy("title"), max_length=255)
103 text = models.TextField(blank=True, null=True)
104 url = models.URLField(blank=True, null=True)
105 email = models.EmailField(blank=True, null=True)
106
107
108 # ######### File fields testing
109
110
111 class FileFieldsModel(models.Model):
112 title = models.CharField(gettext_lazy("title"), max_length=255)
113 file = models.FileField(upload_to="modeltranslation_tests", null=True, blank=True)
114 file2 = models.FileField(upload_to="modeltranslation_tests")
115 image = models.ImageField(upload_to="modeltranslation_tests", null=True, blank=True)
116
117
118 # ######### Foreign Key / OneToOneField / ManytoManyField testing
119
120
121 class NonTranslated(models.Model):
122 title = models.CharField(gettext_lazy("title"), max_length=255)
123
124
125 class ForeignKeyModel(models.Model):
126 title = models.CharField(gettext_lazy("title"), max_length=255)
127 test = models.ForeignKey(
128 TestModel,
129 null=True,
130 related_name="test_fks",
131 on_delete=models.CASCADE,
132 )
133 optional = models.ForeignKey(TestModel, blank=True, null=True, on_delete=models.CASCADE)
134 hidden = models.ForeignKey(
135 TestModel,
136 blank=True,
137 null=True,
138 related_name="+",
139 on_delete=models.CASCADE,
140 )
141 non = models.ForeignKey(
142 NonTranslated,
143 blank=True,
144 null=True,
145 related_name="test_fks",
146 on_delete=models.CASCADE,
147 )
148 untrans = models.ForeignKey(
149 TestModel,
150 blank=True,
151 null=True,
152 related_name="test_fks_un",
153 on_delete=models.CASCADE,
154 )
155
156
157 class OneToOneFieldModel(models.Model):
158 title = models.CharField(gettext_lazy("title"), max_length=255)
159 test = models.OneToOneField(
160 TestModel,
161 null=True,
162 related_name="test_o2o",
163 on_delete=models.CASCADE,
164 )
165 optional = models.OneToOneField(TestModel, blank=True, null=True, on_delete=models.CASCADE)
166 # No hidden option for OneToOne
167 non = models.OneToOneField(
168 NonTranslated,
169 blank=True,
170 null=True,
171 related_name="test_o2o",
172 on_delete=models.CASCADE,
173 )
174
175
176 class ManyToManyFieldModel(models.Model):
177 title = models.CharField(gettext_lazy("title"), max_length=255)
178 test = models.ManyToManyField(
179 TestModel,
180 related_name="m2m_test_ref",
181 )
182 self_call_1 = models.ManyToManyField("self")
183 # test multiple self m2m
184 self_call_2 = models.ManyToManyField("self")
185 through_model = models.ManyToManyField[TestModel, "CustomThroughModel"](
186 TestModel, through="CustomThroughModel"
187 )
188 trans_through_model = models.ManyToManyField[TestModel, Any](
189 TestModel, related_name="m2m_trans_through_model_ref", through="RegisteredThroughModel"
190 )
191 untrans = models.ManyToManyField(
192 NonTranslated,
193 related_name="m2m_untrans_ref",
194 )
195
196
197 class CustomThroughModel(models.Model):
198 rel_1 = models.ForeignKey(ManyToManyFieldModel, on_delete=models.CASCADE)
199 rel_2 = models.ForeignKey(TestModel, on_delete=models.CASCADE)
200
201 @property
202 def test_property(self):
203 return "{}_{}".format(self.__class__.__name__, self.rel_1_id)
204
205 def test_method(self):
206 return self.rel_1_id + 1
207
208
209 class RegisteredThroughModel(models.Model):
210 rel_1 = models.ForeignKey(ManyToManyFieldModel, on_delete=models.CASCADE)
211 rel_2 = models.ForeignKey(TestModel, on_delete=models.CASCADE)
212 title = models.CharField(max_length=255)
213
214
215 # ######### Custom fields testing
216
217
218 class OtherFieldsModel(models.Model):
219 """
220 This class is supposed to include other newly added fields types, so that
221 adding new supported field doesn't end in adding new test model.
222 """
223
224 # That's rich! PositiveIntegerField is only validated in forms, not in models.
225 int = models.PositiveIntegerField(default=42, validators=[validators.MinValueValidator(0)])
226 boolean = models.BooleanField(default=False)
227 float = models.FloatField(blank=True, null=True)
228 decimal = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
229 date = models.DateField(blank=True, null=True)
230 datetime = models.DateTimeField(blank=True, null=True)
231 time = models.TimeField(blank=True, null=True)
232 genericip = models.GenericIPAddressField(blank=True, null=True)
233 json = models.JSONField(blank=True, null=True)
234 json_with_default_dict = models.JSONField(default=dict)
235 json_with_default_list = models.JSONField(default=list)
236
237
238 class FancyDescriptor:
239 """
240 Stupid demo descriptor, that store int in database and return string of that length on get.
241 """
242
243 def __init__(self, field):
244 self.field = field
245
246 def __get__(self, instance, owner):
247 length = instance.__dict__[self.field.name]
248 if length is None:
249 return ""
250 return "a" * length
251
252 def __set__(self, obj, value):
253 if isinstance(value, int):
254 obj.__dict__[self.field.name] = value
255 elif isinstance(value, str):
256 obj.__dict__[self.field.name] = len(value)
257 else:
258 obj.__dict__[self.field.name] = 0
259
260
261 class FancyField(models.PositiveIntegerField):
262 def __init__(self, *args, **kwargs):
263 kwargs.setdefault("default", "")
264 super().__init__(*args, **kwargs)
265
266 def contribute_to_class(self, cls, name):
267 super().contribute_to_class(cls, name)
268 setattr(cls, self.name, FancyDescriptor(self))
269
270 def pre_save(self, model_instance, add):
271 value = super().pre_save(model_instance, add)
272 # In this part value should be retrieved using descriptor and be a string
273 assert isinstance(value, str)
274 # We put an int to database
275 return len(value)
276
277
278 class DescriptorModel(models.Model):
279 normal = FancyField()
280 trans = FancyField()
281
282
283 # ######### Multitable inheritance testing
284
285
286 class MultitableModelA(models.Model):
287 titlea = models.CharField(gettext_lazy("title a"), max_length=255)
288
289
290 class MultitableModelB(MultitableModelA):
291 titleb = models.CharField(gettext_lazy("title b"), max_length=255)
292
293
294 class MultitableModelC(MultitableModelB):
295 titlec = models.CharField(gettext_lazy("title c"), max_length=255)
296
297
298 class MultitableModelD(MultitableModelB):
299 titled = models.CharField(gettext_lazy("title d"), max_length=255)
300
301
302 # ######### Abstract inheritance testing
303
304
305 class AbstractModelA(models.Model):
306 titlea = models.CharField(gettext_lazy("title a"), max_length=255)
307
308 def __init__(self, *args, **kwargs):
309 super().__init__(*args, **kwargs)
310 self.titlea = "title_a"
311
312 class Meta:
313 abstract = True
314
315
316 class AbstractModelB(AbstractModelA):
317 titleb = models.CharField(gettext_lazy("title b"), max_length=255)
318
319 def __init__(self, *args, **kwargs):
320 super().__init__(*args, **kwargs)
321 self.titleb = "title_b"
322
323
324 # ######### Fields inheritance testing
325
326
327 class Slugged(models.Model):
328 slug = models.CharField(max_length=255)
329
330 class Meta:
331 abstract = True
332
333
334 class MetaData(models.Model):
335 keywords = models.CharField(max_length=255)
336
337 class Meta:
338 abstract = True
339
340
341 class Displayable(Slugged, MetaData):
342 class Meta:
343 abstract = True
344
345
346 class BasePage(Displayable):
347 class Meta:
348 abstract = True
349
350
351 class Page(BasePage):
352 title = models.CharField(max_length=255)
353
354
355 class RichText(models.Model):
356 content = models.CharField(max_length=255)
357
358 class Meta:
359 abstract = True
360
361
362 class RichTextPage(Page, RichText):
363 pass
364
365
366 # ######### Admin testing
367
368
369 class DataModel(models.Model):
370 data = models.TextField(blank=True, null=True)
371
372
373 class GroupFieldsetsModel(models.Model):
374 title = models.CharField(max_length=255)
375 text = models.TextField(blank=True, null=True)
376 email = models.EmailField(blank=True, null=True)
377
378
379 class NameModel(models.Model):
380 firstname = models.CharField(max_length=50)
381 lastname = models.CharField(max_length=50)
382 age = models.CharField(max_length=50)
383 slug = models.SlugField(max_length=100)
384 slug2 = models.SlugField(max_length=100)
385
386
387 # ######### Integration testing
388
389
390 class ThirdPartyModel(models.Model):
391 name = models.CharField(max_length=20)
392
393
394 class ThirdPartyRegisteredModel(models.Model):
395 name = models.CharField(max_length=20)
396
397
398 # ######### Manager testing
399 class FilteredManager(MultilingualManager):
400 def get_queryset(self):
401 # always return empty queryset
402 return super().get_queryset().filter(pk=None)
403
404
405 class FilteredTestModel(models.Model):
406 title = models.CharField(gettext_lazy("title"), max_length=255)
407 objects = FilteredManager()
408
409
410 class ForeignKeyFilteredModel(models.Model):
411 title = models.CharField(gettext_lazy("title"), max_length=255)
412 test = models.ForeignKey(
413 FilteredTestModel,
414 null=True,
415 related_name="test_fks",
416 on_delete=models.CASCADE,
417 )
418
419
420 class ManagerTestModel(models.Model):
421 title = models.CharField(gettext_lazy("title"), max_length=255)
422 visits = models.IntegerField(gettext_lazy("visits"), default=0)
423 description = models.CharField(max_length=255, null=True)
424
425 class Meta:
426 ordering = ("-visits",)
427
428
429 class CustomManager(models.Manager):
430 def get_queryset(self):
431 return super().get_queryset().filter(title__contains="a").exclude(description__contains="x")
432
433 def custom_qs(self):
434 return super().get_queryset()
435
436 def foo(self):
437 return "bar"
438
439
440 class CustomManagerTestModel(models.Model):
441 title = models.CharField(gettext_lazy("title"), max_length=255)
442 description = models.CharField(max_length=255, null=True, db_column="xyz")
443 objects = CustomManager()
444
445 another_mgr_name = CustomManager()
446
447
448 class CustomQuerySet(models.query.QuerySet):
449 pass
450
451
452 class CustomManager2(models.Manager):
453 def get_queryset(self):
454 return CustomQuerySet(self.model, using=self._db)
455
456
457 class CustomManager2TestModel(models.Model):
458 title = models.CharField(gettext_lazy("title"), max_length=255)
459 objects = CustomManager2()
460
461
462 class CustomManagerAbstract(models.Manager):
463 pass
464
465
466 class CustomManagerBaseModel(models.Model):
467 needs_translation = models.BooleanField(default=False)
468
469 objects = models.Manager() # ensures objects is the default manager
470 translations = CustomManagerAbstract()
471
472 class Meta:
473 abstract = True
474
475
476 class CustomManagerChildTestModel(CustomManagerBaseModel):
477 title = models.CharField(gettext_lazy("title"), max_length=255)
478
479 objects = CustomManager2() # type: ignore[misc]
480
481
482 class PlainChildTestModel(CustomManagerBaseModel):
483 title = models.CharField(gettext_lazy("title"), max_length=255)
484
485
486 # ######### Required fields testing
487
488
489 class RequiredModel(models.Model):
490 non_req = models.CharField(max_length=10, blank=True)
491 req = models.CharField(max_length=10)
492 req_reg = models.CharField(max_length=10)
493 req_en_reg = models.CharField(max_length=10)
494
495
496 # ######### Name collision registration testing
497
498
499 class ConflictModel(models.Model):
500 title = models.CharField(gettext_lazy("title"), max_length=255)
501 title_de = models.IntegerField()
502
503
504 class AbstractConflictModelA(models.Model):
505 title_de = models.IntegerField()
506
507 class Meta:
508 abstract = True
509
510
511 class AbstractConflictModelB(AbstractConflictModelA):
512 title = models.CharField(gettext_lazy("title"), max_length=255)
513
514
515 class MultitableConflictModelA(models.Model):
516 title_de = models.IntegerField()
517
518
519 class MultitableConflictModelB(MultitableConflictModelA):
520 title = models.CharField(gettext_lazy("title"), max_length=255)
521
522
523 # ######### Complex M2M with abstract classes and custom managers
524
525
526 class CustomQuerySetX(models.query.QuerySet):
527 pass
528
529
530 class CustomManagerX(models.Manager):
531 def get_queryset(self):
532 return CustomQuerySetX(self.model, using=self._db)
533
534
535 class AbstractBaseModelX(models.Model):
536 name = models.CharField(max_length=255)
537 objects = CustomManagerX()
538
539 class Meta:
540 abstract = True
541
542
543 class AbstractModelX(AbstractBaseModelX):
544 class Meta:
545 abstract = True
546
547
548 class ModelX(AbstractModelX):
549 pass
550
551
552 class AbstractModelXY(models.Model):
553 model_x = models.ForeignKey("ModelX", on_delete=models.CASCADE)
554 model_y = models.ForeignKey("ModelY", on_delete=models.CASCADE)
555
556 class Meta:
557 abstract = True
558
559
560 class ModelXY(AbstractModelXY):
561 pass
562
563
564 class CustomManagerY(models.Manager):
565 pass
566
567
568 class AbstractModelY(models.Model):
569 title = models.CharField(max_length=255)
570 xs = models.ManyToManyField[ModelX, ModelXY]("ModelX", through="ModelXY")
571 objects = CustomManagerY()
572
573 class Meta:
574 abstract = True
575
576
577 class ModelY(AbstractModelY):
578 pass
579
580
581 # ######### Non-abstract base models whose Manager is not allowed to be overwritten
582
583
584 class InheritedPermission(Permission):
585 translated_var = models.CharField(max_length=255)
586
587
588 # ######### field_options testing
589
590
591 class FieldOptionsModel(models.Model):
592 title = models.CharField(max_length=255)
593 sub_title1 = models.CharField(max_length=255)
594 sub_title2 = models.CharField(max_length=255)