-
Notifications
You must be signed in to change notification settings - Fork 25
INTPYTHON-658 Add PolymorphicEmbeddedModelArrayField #335
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
54bc945
Rename field in PolymorphicEmbeddedModelField test models
timgraham 68b28bd
Reuse array field logic in DatabaseOperations.get_db_converters()
timgraham f5c491b
INTPYTHON-658 Add PolymorphicEmbeddedModelArrayField
timgraham 6d1f396
Fix typo in EmbeddedModelArrayField.contribute_to_class() comment
timgraham File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
110 changes: 110 additions & 0 deletions
110
django_mongodb_backend/fields/polymorphic_embedded_model_array.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
import contextlib | ||
|
||
from django.core.exceptions import FieldDoesNotExist | ||
from django.db.models.expressions import Col | ||
from django.db.models.fields.related import lazy_related_operation | ||
from django.db.models.lookups import Lookup, Transform | ||
|
||
from . import PolymorphicEmbeddedModelField | ||
from .array import ArrayField, ArrayLenTransform | ||
from .embedded_model_array import KeyTransform as ArrayFieldKeyTransform | ||
from .embedded_model_array import KeyTransformFactory as ArrayFieldKeyTransformFactory | ||
|
||
|
||
class PolymorphicEmbeddedModelArrayField(ArrayField): | ||
def __init__(self, embedded_models, **kwargs): | ||
if "size" in kwargs: | ||
raise ValueError("PolymorphicEmbeddedModelArrayField does not support size.") | ||
kwargs["editable"] = False | ||
super().__init__(PolymorphicEmbeddedModelField(embedded_models), **kwargs) | ||
self.embedded_models = embedded_models | ||
|
||
def contribute_to_class(self, cls, name, private_only=False, **kwargs): | ||
super().contribute_to_class(cls, name, private_only=private_only, **kwargs) | ||
|
||
if not cls._meta.abstract: | ||
# If embedded_models contains any strings, replace them with the actual | ||
# model classes. | ||
def _resolve_lookup(_, *resolved_models): | ||
self.embedded_models = resolved_models | ||
|
||
lazy_related_operation(_resolve_lookup, cls, *self.embedded_models) | ||
|
||
def deconstruct(self): | ||
name, path, args, kwargs = super().deconstruct() | ||
if path == ( | ||
"django_mongodb_backend.fields.polymorphic_embedded_model_array." | ||
"PolymorphicEmbeddedModelArrayField" | ||
): | ||
path = "django_mongodb_backend.fields.PolymorphicEmbeddedModelArrayField" | ||
kwargs["embedded_models"] = self.embedded_models | ||
del kwargs["base_field"] | ||
del kwargs["editable"] | ||
return name, path, args, kwargs | ||
|
||
def get_db_prep_value(self, value, connection, prepared=False): | ||
if isinstance(value, list | tuple): | ||
# Must call get_db_prep_save() rather than get_db_prep_value() | ||
# to transform model instances to dicts. | ||
return [self.base_field.get_db_prep_save(i, connection) for i in value] | ||
if value is not None: | ||
raise TypeError( | ||
f"Expected list of {self.embedded_models!r} instances, not {type(value)!r}." | ||
) | ||
return value | ||
|
||
def formfield(self, **kwargs): | ||
raise NotImplementedError("PolymorphicEmbeddedModelField does not support forms.") | ||
|
||
_get_model_from_label = PolymorphicEmbeddedModelField._get_model_from_label | ||
|
||
def get_transform(self, name): | ||
transform = super().get_transform(name) | ||
if transform: | ||
return transform | ||
return KeyTransformFactory(name, self) | ||
|
||
def _get_lookup(self, lookup_name): | ||
lookup = super()._get_lookup(lookup_name) | ||
if lookup is None or lookup is ArrayLenTransform: | ||
return lookup | ||
|
||
class EmbeddedModelArrayFieldLookups(Lookup): | ||
def as_mql(self, compiler, connection): | ||
raise ValueError( | ||
"Lookups aren't supported on PolymorphicEmbeddedModelArrayField. " | ||
"Try querying one of its embedded fields instead." | ||
) | ||
|
||
return EmbeddedModelArrayFieldLookups | ||
|
||
|
||
class KeyTransform(ArrayFieldKeyTransform): | ||
field_class_name = "PolymorphicEmbeddedModelArrayField" | ||
|
||
def __init__(self, key_name, array_field, *args, **kwargs): | ||
# Skip ArrayFieldKeyTransform.__init__() | ||
Transform.__init__(self, *args, **kwargs) | ||
self.array_field = array_field | ||
self.key_name = key_name | ||
for model in array_field.base_field.embedded_models: | ||
with contextlib.suppress(FieldDoesNotExist): | ||
field = model._meta.get_field(key_name) | ||
break | ||
else: | ||
raise FieldDoesNotExist( | ||
f"The models of field '{array_field.name}' have no field named '{key_name}'." | ||
) | ||
# Lookups iterate over the array of embedded models. A virtual column | ||
# of the queried field's type represents each element. | ||
column_target = field.clone() | ||
column_name = f"$item.{key_name}" | ||
column_target.db_column = column_name | ||
column_target.set_attributes_from_name(column_name) | ||
self._lhs = Col(None, column_target) | ||
self._sub_transform = None | ||
|
||
|
||
class KeyTransformFactory(ArrayFieldKeyTransformFactory): | ||
def __call__(self, *args, **kwargs): | ||
return KeyTransform(self.key_name, self.base_field, *args, **kwargs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -89,7 +89,7 @@ def convert_value(value, expression, connection): | |
def get_db_converters(self, expression): | ||
converters = super().get_db_converters(expression) | ||
internal_type = expression.output_field.get_internal_type() | ||
if internal_type == "ArrayField": | ||
if internal_type.endswith("ArrayField"): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🚀 |
||
converters.extend( | ||
[ | ||
self._get_arrayfield_converter(converter) | ||
|
@@ -111,15 +111,6 @@ def get_db_converters(self, expression): | |
converters.append(self.convert_decimalfield_value) | ||
elif internal_type == "EmbeddedModelField": | ||
converters.append(self.convert_embeddedmodelfield_value) | ||
elif internal_type == "EmbeddedModelArrayField": | ||
converters.extend( | ||
[ | ||
self._get_arrayfield_converter(converter) | ||
for converter in self.get_db_converters( | ||
Expression(output_field=expression.output_field.base_field) | ||
) | ||
] | ||
) | ||
elif internal_type == "JSONField": | ||
converters.append(self.convert_jsonfield_value) | ||
elif internal_type == "PolymorphicEmbeddedModelField": | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How could this class ever come back as an abstract one?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the field is declared on an abstract model.
(The condition is copied from
django.db.models.fields.related.RelatedField.contribute_to_class()
.)