When using the HyperlinkedModelSerializer
from Django REST Framework, the field id
is not included in the fields
by default. This question has an answer that explains that well.
However I have a problem I'd like to solve in a particular way.
I have a model with custom ID and few dozens of other fields:
class Foo(models.Model):
id = models.IntegerField(primary_key=True)
# 20-30 fields
In the serializers.py
I'd like to include all fields from the model:
class FooSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Foo
fields = '__all__'
However this doesn't include the field id
. Defining id = serializers.ReadOnlyField()
doesn't help me either, as id
shoud be editable.
Specifying all the fields manually like this:
fields = ('id', # all other fields)
would be a solution I'm trying to circumvent because the model class has a lot of fields and they might change in future.
Is there an elegant possibility to add the field id
? Maybe overriding the __init__
method?
Add id
attribute in FooSerializer
serializer as:
class FooSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
class Meta:
model = Foo
fields = '__all__'
You can create your custom HyperlinkedModelSerializer and override get_default_field_names
to include the id like normal ModelSerializer does.
Example:
class CustomHyperlinkedModelSerializer(HyperlinkedModelSerializer ):
def get_default_field_names(self, declared_fields, model_info):
return (
[model_info.pk.name] +
[self.url_field_name] +
list(declared_fields) +
list(model_info.fields) +
list(model_info.forward_relations)
)
Note : this is just an idea. I have not tested it yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With