Skip to content

Instantly share code, notes, and snippets.

@ostcar
Last active October 28, 2023 10:34
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ostcar/eb78515a41ab41d1755b to your computer and use it in GitHub Desktop.
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
Copy link

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