简体   繁体   中英

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?

Add id attribute in FooSerializer serializer as:

class FooSerializer(serializers.HyperlinkedModelSerializer):
    
    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.

HyperlinkedModelSerializer doesn't include the id field by default. You can include id by adding it to the serializer as an attribute like this:

class FooSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.IntegerField()
    class Meta:
        model = Foo
        fields = '__all__'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM