Skip to content
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

Feature/allow renaming expandable foreign keys #42

Merged
merged 1 commit into from
Jun 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .bumpversion.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[bumpversion]
current_version = 0.20.0
current_version = 0.21.0

[bumpversion:file:setup.py]

Expand Down
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ and this project adheres to [Semantic
Versioning](https://semver.org/spec/v2.0.0.html).


# [Unrelased]
# [0.21.0]
### Added
- [PR 42](/~https://github.com/salesforce/django-declarative-apis/pull/42) Add inst_field_name to expandable fields
### Changed
- [PR 39](/~https://github.com/salesforce/django-declarative-apis/pull/39) Add long_description to setup
- [PR 40](/~https://github.com/salesforce/django-declarative-apis/pull/40) Remove use of root logger
Expand Down
26 changes: 17 additions & 9 deletions django_declarative_apis/machinery/filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,40 +21,44 @@


class _ExpandableForeignKey:
def __init__(self, display_key, model_class):
def __init__(self, display_key, model_class, inst_field_name):
self.display_key = display_key
self.model_class = model_class
self.inst_field_name = inst_field_name


def expandable(model_class=None, display_key=None):
def expandable(model_class=None, display_key=None, inst_field_name=None):
if model_class and not issubclass(model_class, (models.Model,)):
raise ValueError("model_class must be an instance of a Django Model")
if model_class and display_key:
try:
model_class._meta.get_field(display_key)
except models.FieldDoesNotExist as e: # noqa
raise ValueError(f"{display_key} is not a field on {model_class.__name__}")
return _ExpandableForeignKey(display_key, model_class)
return _ExpandableForeignKey(display_key, model_class, inst_field_name)


def _get_unexpanded_field_value(inst, field_name, field_type):
if not field_type.model_class:
return DEFAULT_UNEXPANDED_VALUE

display_key = field_type.display_key or field_type.model_class._meta.pk.name
is_multiple = isinstance(inst.__class__._meta.get_field(field_name), ManyToOneRel)
inst_field_name = field_type.inst_field_name or field_name
is_multiple = isinstance(
inst.__class__._meta.get_field(inst_field_name), ManyToOneRel
)

if is_multiple:
# special case for keys that have multiple values (for instance, inverse fk relations)
obj = getattr(inst, field_name)
obj = getattr(inst, inst_field_name)
return [{display_key: getattr(v, display_key)} for v in obj.all()]

if display_key == field_type.model_class._meta.pk.name:
# special case - we know this is a primary key, so we can get it without retrieving the object
return {display_key: getattr(inst, field_name + "_id")}
return {display_key: getattr(inst, inst_field_name + "_id")}
else:
# we're not returning the PK - have to actually retrieve the model
obj = getattr(inst, field_name)
obj = getattr(inst, inst_field_name)
return {display_key: getattr(obj, display_key)}


Expand All @@ -67,8 +71,12 @@ def _get_filtered_field_value(

if isinstance(field_type, types.FunctionType):
val = field_type(inst)
elif isinstance(field_type, _ExpandableForeignKey) and not expand_this:
val = _get_unexpanded_field_value(inst, field_name, field_type)
elif isinstance(field_type, _ExpandableForeignKey):
if expand_this:
inst_field_name = field_type.inst_field_name or field_name
val = getattr(inst, inst_field_name)
else:
val = _get_unexpanded_field_value(inst, field_name, field_type)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't need the same inst_field_name treatment because it's not actually hitting the model, right?

Copy link
Collaborator Author

@dshafer dshafer Jun 9, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it does need it, and accesses it within the called function as field_type.inst_field_name (line 46)

else:
try:
val = getattr(inst, field_name)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

setuptools.setup(
name="django-declarative-apis",
version="0.20.0", # set by bumpversion
version="0.21.0", # set by bumpversion
author="Drew Shafer",
url="https://salesforce.com",
description="Simple, readable, declarative APIs for Django",
Expand Down
28 changes: 28 additions & 0 deletions tests/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,34 @@
},
}

RENAMED_EXPANDABLE_MODEL_FIELDS = {
str: ALWAYS,
int: ALWAYS,
dict: ALWAYS,
models.TestModel: {
"pk": ALWAYS,
"int_field": ALWAYS,
"renamed_expandable_dict": expandable(inst_field_name="expandable_dict"),
"renamed_expandable_string": expandable(inst_field_name="expandable_string"),
},
models.ParentModel: {
"nonstandard_id": ALWAYS,
"name": ALWAYS,
"favorite": expandable(model_class=models.ChildModel, display_key="name"),
"children": expandable(model_class=models.ChildModel, display_key="name"),
},
models.ChildModel: {
"pk": ALWAYS,
"renamed_test": expandable(
model_class=models.TestModel, inst_field_name="test"
),
"name": ALWAYS,
"renamed_parent": expandable(
model_class=models.ParentModel, inst_field_name="parent"
),
},
}

DEFAULT_FILTERS_NO_EXPANDABLE = {
str: ALWAYS,
int: ALWAYS,
Expand Down
42 changes: 42 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,45 @@ def test_expandable_absent_if_no_expandable_fields(self):
self.assertEqual(
filtered["expandable_string"], models.TestModel.EXPANDABLE_STRING_RETURN
)

def test_rename_expandable_foreign_key(self):
filtered = filtering.apply_filters_to_object(
self.p1c1, filters.RENAMED_EXPANDABLE_MODEL_FIELDS
)

self.assertEqual(filtered["renamed_test"], {"id": self.p1c1.test.pk})
self.assertEqual(
filtered["renamed_parent"], {"nonstandard_id": self.p1c1.parent.pk}
)

filtered = filtering.apply_filters_to_object(
self.p1c1,
filters.RENAMED_EXPANDABLE_MODEL_FIELDS,
expand_header="renamed_test,renamed_parent",
)
self.assertTrue(2, len(filtered["renamed_test"]))
self.assertIn("int_field", filtered["renamed_test"])
self.assertNotIn("renamed_expandable_dict", filtered["renamed_test"])
self.assertTrue(4, len(filtered["renamed_parent"]))

filtered = filtering.apply_filters_to_object(
self.p1c1,
filters.RENAMED_EXPANDABLE_MODEL_FIELDS,
expand_header="renamed_test,renamed_test.renamed_expandable_dict",
)
self.assertTrue(3, len(filtered["renamed_test"]))
self.assertIn("renamed_expandable_dict", filtered["renamed_test"])
self.assertEqual(
self.test_model.expandable_dict,
filtered["renamed_test"]["renamed_expandable_dict"],
)
self.assertNotIn("renamed_expandable_string", filtered["renamed_test"])

filtered = filtering.apply_filters_to_object(
self.p1c1,
filters.RENAMED_EXPANDABLE_MODEL_FIELDS,
expand_header="renamed_test,renamed_test.renamed_expandable_dict,renamed_test.renamed_expandable_string",
)
self.assertTrue(4, len(filtered["renamed_test"]))
self.assertIn("renamed_expandable_dict", filtered["renamed_test"])
self.assertIn("renamed_expandable_string", filtered["renamed_test"])