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

Support nullable foreign keys with read_only=False #25

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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: 2 additions & 0 deletions docs/usage-serializers.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ It is important to note that we are passing an organization's ID to the
`organization_id` field, not a dictionary of properties to the `organization`
field.

To support nullable foreign key relationship in writable situation, set `allow_null=True` after `read_only=False`.

During validation the serializer will find the corresponding organization and
add make it available in the deserialized data under the key
`organization_id_resolved`:
Expand Down
7 changes: 6 additions & 1 deletion rest_framework_serializer_extensions/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,8 @@ def get_expand_id_field(self, field_name, field_definition):
utils.model_from_definition(field_definition['id_model'])
.objects.all()
)
if 'allow_null' in field_definition.keys():
Copy link
Owner

Choose a reason for hiding this comment

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

Wouldn't this be better as field_definition.get('allow_null')?

kwargs['allow_null'] = field_definition['allow_null']

return serializers.PrimaryKeyRelatedField(**kwargs)

Expand Down Expand Up @@ -686,7 +688,10 @@ def run_validation(self, data=empty):
validated_data[resolved_field_name] = instance

# Translate ID field contents back to an ID
validated_data[id_field_name] = instance.pk
if instance is None:
validated_data[id_field_name] = None
else:
validated_data[id_field_name] = instance.pk

return validated_data

Expand Down