|
| 1 | +from django.core.exceptions import ValidationError |
1 | 2 | from django.db import models |
| 3 | +from mptt.exceptions import InvalidMove |
2 | 4 |
|
3 | 5 | from polymorphic.showfields import ShowFieldContent |
4 | 6 | from polymorphic_tree.models import PolymorphicMPTTModel, PolymorphicTreeForeignKey |
@@ -46,3 +48,81 @@ class ModelX(Base): |
46 | 48 |
|
47 | 49 | class ModelY(Base): |
48 | 50 | field_y = models.CharField(max_length=10) |
| 51 | + |
| 52 | + |
| 53 | +class ModelWithCustomParentName(PolymorphicMPTTModel): |
| 54 | + """Model with custom parent name |
| 55 | +
|
| 56 | + A model where ``PolymorphicTreeForeignKey`` attribute has not ``parent`` |
| 57 | + name, but ``chief`` |
| 58 | +
|
| 59 | + Attributes: |
| 60 | + chief (ModelWithCustomParentName): parent |
| 61 | + field5 (str): test field |
| 62 | + """ |
| 63 | + chief = PolymorphicTreeForeignKey('self', |
| 64 | + blank=True, |
| 65 | + null=True, |
| 66 | + related_name='subordinate', |
| 67 | + verbose_name='Chief') |
| 68 | + field5 = models.CharField(max_length=10) |
| 69 | + |
| 70 | + class MPTTMeta: |
| 71 | + parent_attr = 'chief' |
| 72 | + |
| 73 | + def __str__(self): |
| 74 | + return self.field5 |
| 75 | + |
| 76 | + |
| 77 | +class ModelWithValidation(PolymorphicMPTTModel): |
| 78 | + """Model with custom validation |
| 79 | +
|
| 80 | + A model with redefined ``clean`` and ``can_be_moved`` methods |
| 81 | +
|
| 82 | + ``clean`` method always raises ``ValidationError`` |
| 83 | + ``can_be_moved`` always calls ``clean`` |
| 84 | +
|
| 85 | + Attributes: |
| 86 | + parent (ModelWithValidation): parent |
| 87 | + field6 (str): test field |
| 88 | + """ |
| 89 | + |
| 90 | + parent = PolymorphicTreeForeignKey('self', |
| 91 | + blank=True, |
| 92 | + null=True, |
| 93 | + related_name='children') |
| 94 | + |
| 95 | + field6 = models.CharField(max_length=10) |
| 96 | + |
| 97 | + def clean(self): |
| 98 | + """Raise validation error""" |
| 99 | + raise ValidationError({ |
| 100 | + 'parent': 'There is something with parent field' |
| 101 | + }) |
| 102 | + |
| 103 | + def can_be_moved(self, target): |
| 104 | + """Execute ``clean``""" |
| 105 | + self.clean() |
| 106 | + |
| 107 | + |
| 108 | +class ModelWithInvalidMove(PolymorphicMPTTModel): |
| 109 | + """Model with custom validation |
| 110 | +
|
| 111 | + A model with redefined only ``can_be_moved`` method which always raises |
| 112 | + ``InvalidMove`` |
| 113 | +
|
| 114 | + Attributes: |
| 115 | + parent (ModelWithValidation): parent |
| 116 | + field7 (str): test field |
| 117 | + """ |
| 118 | + |
| 119 | + parent = PolymorphicTreeForeignKey('self', |
| 120 | + blank=True, |
| 121 | + null=True, |
| 122 | + related_name='children') |
| 123 | + |
| 124 | + field7 = models.CharField(max_length=10) |
| 125 | + |
| 126 | + def can_be_moved(self, target): |
| 127 | + """Raise ``InvalidMove``""" |
| 128 | + raise InvalidMove('Invalid move') |
0 commit comments