django-modelcluster 6.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-modelcluster
3
+ Version: 6.5
4
+ Summary: Django extension to allow working with 'clusters' of models as a single unit, independently of the database
5
+ Author-email: Matthew Westcott <matthew.westcott@torchbox.com>, Wagtail Team <hello@wagtail.org>
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Changelog, https://github.com/wagtail/django-modelcluster/blob/main/CHANGELOG.txt
8
+ Project-URL: Homepage, https://github.com/wagtail/django-modelcluster
9
+ Keywords: cluster,django,model
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Environment :: Web Environment
12
+ Classifier: Framework :: Django
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/x-rst
24
+ License-File: LICENSE
25
+ Requires-Dist: django>=4.2
26
+ Provides-Extra: taggit
27
+ Requires-Dist: django-taggit>=3.1; extra == "taggit"
28
+ Dynamic: license-file
29
+
30
+ django-modelcluster
31
+ ===================
32
+
33
+ If you had a data model like this:
34
+
35
+ .. code-block:: python
36
+
37
+ class Band(models.Model):
38
+ name = models.CharField(max_length=255)
39
+
40
+ class BandMember(models.Model):
41
+ band = models.ForeignKey('Band', related_name='members', on_delete=models.CASCADE)
42
+ name = models.CharField(max_length=255)
43
+
44
+
45
+ wouldn't it be nice if you could construct bundles of objects like this, independently of the database:
46
+
47
+ .. code-block:: python
48
+
49
+ beatles = Band(name='The Beatles')
50
+ beatles.members = [
51
+ BandMember(name='John Lennon'),
52
+ BandMember(name='Paul McCartney'),
53
+ ]
54
+
55
+ Unfortunately, you can't. Objects need to exist in the database for foreign key relations to work:
56
+
57
+ .. code-block:: python
58
+
59
+ IntegrityError: null value in column "band_id" violates not-null constraint
60
+
61
+ But what if you could? There are all sorts of scenarios where you might want to work with a 'cluster' of related objects, without necessarily holding them in the database: maybe you want to render a preview of the data the user has just submitted, prior to saving. Maybe you need to construct a tree of things, serialize them and hand them off to some external system. Maybe you have a workflow where your models exist in an incomplete 'draft' state for an extended time, or you need to handle multiple revisions, and you don't want to redesign your database around that requirement.
62
+
63
+ **django-modelcluster** extends Django's foreign key relations to make this possible. It introduces a new type of relation, *ParentalKey*, where the related models are stored locally to the 'parent' model until the parent is explicitly saved. Up to that point, the related models can still be accessed through a subset of the QuerySet API:
64
+
65
+ .. code-block:: python
66
+
67
+ from modelcluster.models import ClusterableModel
68
+ from modelcluster.fields import ParentalKey
69
+
70
+
71
+ class Band(ClusterableModel):
72
+ name = models.CharField(max_length=255)
73
+
74
+ class BandMember(models.Model):
75
+ band = ParentalKey('Band', related_name='members', on_delete=models.CASCADE)
76
+ name = models.CharField(max_length=255)
77
+
78
+
79
+ >>> beatles = Band(name='The Beatles')
80
+ >>> beatles.members = [
81
+ ... BandMember(name='John Lennon'),
82
+ ... BandMember(name='Paul McCartney'),
83
+ ... ]
84
+ >>> [member.name for member in beatles.members.all()]
85
+ ['John Lennon', 'Paul McCartney']
86
+ >>> beatles.members.add(BandMember(name='George Harrison'))
87
+ >>> beatles.members.count()
88
+ 3
89
+ >>> beatles.save() # only now are the records written to the database
90
+
91
+ For more examples, see the unit tests.
92
+
93
+
94
+ Many-to-many relations
95
+ ----------------------
96
+
97
+ For many-to-many relations, a corresponding *ParentalManyToManyField* is available:
98
+
99
+ .. code-block:: python
100
+
101
+ from modelcluster.models import ClusterableModel
102
+ from modelcluster.fields import ParentalManyToManyField
103
+
104
+ class Movie(ClusterableModel):
105
+ title = models.CharField(max_length=255)
106
+ actors = ParentalManyToManyField('Actor', related_name='movies')
107
+
108
+ class Actor(models.Model):
109
+ name = models.CharField(max_length=255)
110
+
111
+
112
+ >>> harrison_ford = Actor.objects.create(name='Harrison Ford')
113
+ >>> carrie_fisher = Actor.objects.create(name='Carrie Fisher')
114
+ >>> star_wars = Movie(title='Star Wars')
115
+ >>> star_wars.actors = [harrison_ford, carrie_fisher]
116
+ >>> blade_runner = Movie(title='Blade Runner')
117
+ >>> blade_runner.actors.add(harrison_ford)
118
+ >>> star_wars.actors.count()
119
+ 2
120
+ >>> [movie.title for movie in harrison_ford.movies.all()] # the Movie records are not in the database yet
121
+ []
122
+ >>> star_wars.save() # Star Wars now exists in the database (along with the 'actor' relations)
123
+ >>> [movie.title for movie in harrison_ford.movies.all()]
124
+ ['Star Wars']
125
+
126
+ Note that ``ParentalManyToManyField`` is defined on the parent model rather than the related model, just as a standard ``ManyToManyField`` would be. Also note that the related objects - the ``Actor`` instances in the above example - must exist in the database before being associated with the parent record. (The ``ParentalManyToManyField`` allows the relations between Movies and Actors to be stored in memory without writing to the database, but not the ``Actor`` records themselves.)
127
+
128
+
129
+ Introspection
130
+ -------------
131
+ If you need to find out which child relations exist on a parent model - to create a deep copy of the model and all its children, say - use the ``modelcluster.models.get_all_child_relations`` function:
132
+
133
+ .. code-block:: python
134
+
135
+ >>> from modelcluster.models import get_all_child_relations
136
+ >>> get_all_child_relations(Band)
137
+ [<RelatedObject: tests:bandmember related to band>, <RelatedObject: tests:album related to band>]
138
+
139
+ This includes relations that are defined on any superclasses of the parent model.
140
+
141
+ To retrieve a list of all ParentalManyToManyFields defined on a parent model, use ``modelcluster.models.get_all_child_m2m_relations``:
142
+
143
+ .. code-block:: python
144
+
145
+ >>> from modelcluster.models import get_all_child_m2m_relations
146
+ >>> get_all_child_m2m_relations(Movie)
147
+ [<modelcluster.fields.ParentalManyToManyField: actors>]
@@ -0,0 +1,15 @@
1
+ django_modelcluster-6.5.dist-info/licenses/LICENSE,sha256=l-Pf7ZCfEQc0xvqoD_9J054OG_g8jWO69lqjXAJU8kw,1550
2
+ modelcluster/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ modelcluster/datetime_utils.py,sha256=pK5TeNJrDHBxslzdT0y3ku3cx60VKDmbfH6XEnH-yvg,3556
4
+ modelcluster/fields.py,sha256=3y1-UxKSLYVHJ5Vb3cZmHPPMnx6-evjSD_bpMLP6vVw,23612
5
+ modelcluster/forms.py,sha256=metWvkuzE31ZdAO1bMYaIgqiaB-fesFqplPbyLYiskk,20527
6
+ modelcluster/models.py,sha256=UFJXC_n9vSw03UDolIa09-fwII3VkSLu8Y8GWyLq8bk,17624
7
+ modelcluster/queryset.py,sha256=Tn5TU5Fml7f65HGvmmH9ZqgAFC4awuGx6soYmh9qygE,18400
8
+ modelcluster/tags.py,sha256=uyOmRcWPmRgMyI_6X_L2hT8AbjJWTMnvEaB8ZtVa5aM,192
9
+ modelcluster/utils.py,sha256=45pNnAUIm4iIjSnad22VvWAfN6U46XCFceGNLQ74uHA,8232
10
+ modelcluster/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ modelcluster/contrib/taggit.py,sha256=HoVkD4mQAAzOGp1dDeieCmqnwihJMahbpcNjAKb7-cI,7411
12
+ django_modelcluster-6.5.dist-info/METADATA,sha256=_qgFAJfXp9eRUTrFhPSg_92ZPIHvJadYfEwGcUY_m_A,6306
13
+ django_modelcluster-6.5.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
14
+ django_modelcluster-6.5.dist-info/top_level.txt,sha256=eeF-kkxQGWl1rPdYPzAIP6UB5G8Hk5twPPb0xhFFDj8,13
15
+ django_modelcluster-6.5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2014-2018 Torchbox Ltd and individual contributors.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification,
5
+ are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of Torchbox nor the names of its contributors may be used
15
+ to endorse or promote products derived from this software without
16
+ specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
22
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ modelcluster
File without changes
File without changes
@@ -0,0 +1,175 @@
1
+ from __future__ import unicode_literals
2
+ from __future__ import absolute_import
3
+
4
+ from taggit import VERSION as TAGGIT_VERSION
5
+ from taggit.managers import TaggableManager, _TaggableManager
6
+ from taggit.utils import require_instance_manager
7
+
8
+ from modelcluster.queryset import FakeQuerySet
9
+
10
+
11
+ if TAGGIT_VERSION < (0, 20, 0):
12
+ raise Exception(
13
+ "modelcluster.contrib.taggit requires django-taggit version 0.20 or above"
14
+ )
15
+
16
+
17
+ class _ClusterTaggableManager(_TaggableManager):
18
+ @require_instance_manager
19
+ def get_tagged_item_manager(self):
20
+ """Return the manager that handles the relation from this instance to the tagged_item class.
21
+ If content_object on the tagged_item class is defined as a ParentalKey, this will be a
22
+ DeferringRelatedManager which allows writing related objects without committing them
23
+ to the database.
24
+ """
25
+ rel_name = self.through._meta.get_field(
26
+ "content_object"
27
+ ).remote_field.get_accessor_name()
28
+ return getattr(self.instance, rel_name)
29
+
30
+ def get_queryset(self, extra_filters=None):
31
+ if self.instance is not None:
32
+ tagged_item_manager = self.get_tagged_item_manager()
33
+
34
+ # If we're already managing tags in memory for this instance,
35
+ # we want to return those uncommitted changes. This shouldn't
36
+ # require a request to the database.
37
+ if tagged_item_manager.is_deferring:
38
+ return FakeQuerySet(
39
+ self.through.tag_model(),
40
+ [tagged_item.tag for tagged_item in tagged_item_manager.all()],
41
+ )
42
+
43
+ # If we don't have any uncommitted changes for this instance,
44
+ # we'd ideally like to use the default taggit logic. There's one
45
+ # case that we need to handle specially, which is the ability to
46
+ # query tags on an unsaved model instance, for example:
47
+ #
48
+ # class TaggedPlace(TaggedItemBase):
49
+ # content_object = ParentalKey(
50
+ # "Place",
51
+ # related_name="tagged_items",
52
+ # on_delete=models.CASCADE,
53
+ # )
54
+ #
55
+ # class Place(ClusterableModel):
56
+ # tags = ClusterTaggableManager(
57
+ # through=TaggedPlace,
58
+ # blank=True,
59
+ # )
60
+ #
61
+ # instance = Place()
62
+ # instance.tags.count()
63
+ #
64
+ # Under the hood this call invokes this get_queryset method with an
65
+ # unsaved self.instance, which would trigger this query using the
66
+ # default taggit logic:
67
+ #
68
+ # TaggedPlace.objects.filter(content_object=Place())
69
+ #
70
+ # This works on Django < 5.0, returning an empty list as expected.
71
+ # But as of Django 5.0, passing unsaved model instances to related
72
+ # filters is no longer allowed, see
73
+ # https://code.djangoproject.com/ticket/31486.
74
+ #
75
+ # To handle this case we return an empty tag list since there won't
76
+ # be any existing tags in the database for an unsaved instance.
77
+ elif self.instance.pk is None:
78
+ return FakeQuerySet(self.through.tag_model(), [])
79
+
80
+ # If we've reached this point then either this manager isn't associated
81
+ # with a specific model, which probably means it's being invoked within
82
+ # a prefetch_related operation:
83
+ #
84
+ # Place.objects.prefetch_related("tags")
85
+ #
86
+ # or we're fetching tags for a model instance that doesn't have any
87
+ # uncommitted tag changes in memory:
88
+ #
89
+ # place = Place.objects.first()
90
+ # place.tags.all()
91
+ #
92
+ # In these cases we can fallback to the default taggit manager behavior
93
+ # which will fetch the tags from the database.
94
+ return super().get_queryset(extra_filters)
95
+
96
+ @require_instance_manager
97
+ def add(self, *tags):
98
+ if TAGGIT_VERSION >= (3, 1, 0):
99
+ self._remove_prefetched_objects()
100
+
101
+ if TAGGIT_VERSION >= (1, 3, 0):
102
+ tag_objs = self._to_tag_model_instances(tags, {})
103
+ else:
104
+ tag_objs = self._to_tag_model_instances(tags)
105
+
106
+ # Now write these to the relation
107
+ tagged_item_manager = self.get_tagged_item_manager()
108
+ for tag in tag_objs:
109
+ if not tagged_item_manager.filter(tag=tag):
110
+ # make an instance of the self.through model and add it to the relation
111
+ tagged_item = self.through(tag=tag)
112
+ tagged_item_manager.add(tagged_item)
113
+
114
+ @require_instance_manager
115
+ def remove(self, *tags):
116
+ if TAGGIT_VERSION >= (3, 1, 0):
117
+ self._remove_prefetched_objects()
118
+
119
+ tagged_item_manager = self.get_tagged_item_manager()
120
+ tagged_items = [
121
+ tagged_item
122
+ for tagged_item in tagged_item_manager.all()
123
+ if tagged_item.tag.name in tags
124
+ ]
125
+ tagged_item_manager.remove(*tagged_items)
126
+
127
+ @require_instance_manager
128
+ def set(self, *args, **kwargs):
129
+ # Ignore the 'clear' kwarg (which defaults to False) and override it to be always true;
130
+ # this means that set is implemented as a clear then an add, which was the standard behaviour
131
+ # prior to django-taggit 0.19 (https://github.com/alex/django-taggit/commit/6542a702b590a5cfb91ea0de218b7f71ffd07c33).
132
+ #
133
+ # In this way, we avoid a live database lookup that occurs in the clear=False branch.
134
+ #
135
+ # The clear=True behaviour is fine for our purposes; the distinction only exists in django-taggit
136
+ # to ensure that the correct set of m2m_changed signals is fired, and our reimplementation here
137
+ # doesn't fire them at all (which makes logical sense, because the whole point of this module is
138
+ # that the add/remove/set/clear operations don't write to the database).
139
+ #
140
+ # super().set() already calls self._remove_prefetched_objects() so we don't need to do so here.
141
+ return super().set(*args, clear=True)
142
+
143
+ @require_instance_manager
144
+ def clear(self):
145
+ if TAGGIT_VERSION >= (3, 1, 0):
146
+ self._remove_prefetched_objects()
147
+ self.get_tagged_item_manager().clear()
148
+
149
+
150
+ class ClusterTaggableManager(TaggableManager):
151
+ _need_commit_after_assignment = True
152
+
153
+ def __get__(self, instance, model):
154
+ # override TaggableManager's requirement for instance to have a primary key
155
+ # before we can access its tags
156
+ manager = _ClusterTaggableManager(
157
+ through=self.through,
158
+ model=model,
159
+ instance=instance,
160
+ prefetch_cache_name=self.name,
161
+ )
162
+
163
+ return manager
164
+
165
+ def value_from_object(self, instance):
166
+ # retrieve the queryset via the related manager on the content object,
167
+ # to accommodate the possibility of this having uncommitted changes relative to
168
+ # the live database
169
+ rel_name = self.through._meta.get_field(
170
+ "content_object"
171
+ ).remote_field.get_accessor_name()
172
+ ret = getattr(instance, rel_name).all()
173
+ if TAGGIT_VERSION >= (1,): # expects a Tag list instead of TaggedItem List
174
+ ret = [tagged_item.tag for tagged_item in ret]
175
+ return ret
@@ -0,0 +1,117 @@
1
+ import datetime
2
+
3
+ from django import forms
4
+
5
+
6
+ TIMEFIELD_TRANSFORM_EXPRESSIONS = {"hour", "minute", "second"}
7
+ DATEFIELD_TRANSFORM_EXPRESSIONS = {
8
+ "year",
9
+ "iso_year",
10
+ "month",
11
+ "day",
12
+ "week",
13
+ "week_day",
14
+ "iso_week_day",
15
+ "quarter",
16
+ }
17
+ DATETIMEFIELD_TRANSFORM_EXPRESSIONS = (
18
+ {"date", "time"} | TIMEFIELD_TRANSFORM_EXPRESSIONS | DATEFIELD_TRANSFORM_EXPRESSIONS
19
+ )
20
+ TRANSFORM_FIELD_TYPES = {
21
+ "year": forms.IntegerField,
22
+ "iso_year": forms.IntegerField,
23
+ "month": forms.IntegerField,
24
+ "hour": forms.IntegerField,
25
+ "minute": forms.IntegerField,
26
+ "second": forms.IntegerField,
27
+ "day": forms.IntegerField,
28
+ "week": forms.IntegerField,
29
+ "week_day": forms.IntegerField,
30
+ "iso_week_day": forms.IntegerField,
31
+ "quarter": forms.IntegerField,
32
+ "date": forms.DateField,
33
+ "time": forms.TimeField,
34
+ }
35
+
36
+
37
+ def derive_from_value(value, expr):
38
+ if isinstance(value, datetime.datetime):
39
+ return derive_from_datetime(value, expr)
40
+ if isinstance(value, datetime.date):
41
+ return derive_from_date(value, expr)
42
+ if isinstance(value, datetime.time):
43
+ return derive_from_time(value, expr)
44
+ return None
45
+
46
+
47
+ def derive_from_time(value, expr):
48
+ """
49
+ Mimics the behaviour of the ``hour``, ``minute`` and ``second`` lookup
50
+ expressions that Django querysets support for ``TimeField`` and
51
+ ``DateTimeField``, by extracting the relevant value from an in-memory
52
+ ``time`` or ``datetime`` value.
53
+ """
54
+ if expr == "hour":
55
+ return value.hour
56
+ if expr == "minute":
57
+ return value.minute
58
+ if expr == "second":
59
+ return value.second
60
+ raise ValueError(
61
+ "Expression '{expression}' is not supported for {value}".format(
62
+ expression=expr, value=repr(value)
63
+ )
64
+ )
65
+
66
+
67
+ def derive_from_date(value, expr):
68
+ """
69
+ Mimics the behaviour of the ``year``, ``iso_year`` ``month``, ``day``,
70
+ ``week``, ``week_day``, ``iso_week_day`` and ``quarter`` lookup
71
+ expressions that Django querysets support for ``DateField`` and
72
+ ``DateTimeField`` columns, by extracting the relevant value from an
73
+ in-memory ``date`` or ``datetime`` value.
74
+ """
75
+ if expr == "year":
76
+ return value.year
77
+ if expr == "iso_year":
78
+ return value.isocalendar()[0]
79
+ if expr == "month":
80
+ return value.month
81
+ if expr == "day":
82
+ return value.day
83
+ if expr == "week":
84
+ return value.isocalendar()[1]
85
+ if expr == "week_day":
86
+ v = value.isoweekday()
87
+ return 1 if v == 7 else v + 1
88
+ if expr == "iso_week_day":
89
+ return value.isoweekday()
90
+ if expr == "quarter":
91
+ return (value.month - 1) // 3 + 1
92
+ raise ValueError(
93
+ "Expression '{expression}' is not supported for {value}".format(
94
+ expression=expr, value=repr(value)
95
+ )
96
+ )
97
+
98
+
99
+ def derive_from_datetime(value, expr):
100
+ """
101
+ Mimics the behaviour of the ``date``, ``time`` and other lookup
102
+ expressions that Django querysets support for ``DateTimeField`` columns,
103
+ by extracting the relevant value from an in-memory ``datetime`` value.
104
+ """
105
+ if expr == "date":
106
+ return value.date()
107
+ if expr == "time":
108
+ return value.time()
109
+ if expr in TIMEFIELD_TRANSFORM_EXPRESSIONS:
110
+ return derive_from_time(value, expr)
111
+ if expr in DATEFIELD_TRANSFORM_EXPRESSIONS:
112
+ return derive_from_date(value, expr)
113
+ raise ValueError(
114
+ "Expression '{expression}' is not supported for {value}".format(
115
+ expression=expr, value=repr(value)
116
+ )
117
+ )