Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adds a _id suffix to PrimaryKeyRelatedField
class IdManyRelatedField(ManyRelatedField):
field_name_suffix = '_ids'
def bind(self, field_name, parent):
self.source = field_name[:-len(self.field_name_suffix)]
super().bind(field_name, parent)
class IdPrimaryKeyRelatedField(PrimaryKeyRelatedField):
"""
Field, that renames the field name to FIELD_NAME_id.
Only works together the our ModelSerializer.
"""
many_related_field_class = IdManyRelatedField
field_name_suffix = '_id'
def bind(self, field_name, parent):
"""
Called when the field is bound to the serializer.
Changes the source so that the original field name is used (removes
the _id suffix).
"""
if field_name:
self.source = field_name[:-len(self.field_name_suffix)]
super().bind(field_name, parent)
class IdModelSerializer(ModelSerializer):
"""
ModelSerializer that changes the field names of related fields to
FIELD_NAME_id.
"""
serializer_related_field = IdPrimaryKeyRelatedField
def get_fields(self):
fields = super().get_fields()
new_fields = type(fields)()
for field_name, field in fields.items():
try:
field_name += field.field_name_suffix
except AttributeError:
pass
new_fields[field_name] = field
return new_fields
@grantm

This comment has been minimized.

Copy link

@grantm grantm commented Mar 4, 2020

Just noting that I've been unable to make the IdModelSerializer work with the UniqueTogetherValidator that results from defining a 'unique_together' constraint on the model.

Apart from that, these classes have been very successful in working around one source of pain in the Django Rest Framework.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment