Last active
October 28, 2023 10:34
-
-
Save ostcar/eb78515a41ab41d1755b to your computer and use it in GitHub Desktop.
Adds a _id suffix to PrimaryKeyRelatedField
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.