Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add 'id' to the fields in HyperlinkedModelSerializer in DRF

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?

like image 452
cezar Avatar asked Jan 28 '23 13:01

cezar


2 Answers

Add id attribute in FooSerializer serializer as:

class FooSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.IntegerField(read_only=True)
    class Meta:
        model = Foo
        fields = '__all__'
like image 104
JPG Avatar answered Jan 31 '23 22:01

JPG


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.

like image 26
Enthusiast Martin Avatar answered Jan 31 '23 21:01

Enthusiast Martin