[英]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. 使用Django REST Framework中的HyperlinkedModelSerializer
,字段id
默认情况下不包含在fields
。 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: 我有一个带有自定义ID的模型和几十个其他领域:
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: 在serializers.py
我想要包含模型中的所有字段:
class FooSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Foo
fields = '__all__'
However this doesn't include the field id
. 但是,这不包括字段id
。 Defining id = serializers.ReadOnlyField()
doesn't help me either, as id
shoud be editable. 定义id = serializers.ReadOnlyField()
对我也没有帮助,因为id
应该是可编辑的。
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
? 是否有添加字段id
的优雅可能性? Maybe overriding the __init__
method? 也许重写__init__
方法?
Add id
attribute in FooSerializer
serializer as: 在FooSerializer
序列化程序中添加id
属性:
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. 您可以创建自定义HyperlinkedModelSerializer并覆盖get_default_field_names
以包含与普通ModelSerializer一样的ID。
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. 默认情况下, HyperlinkedModelSerializer
不包含id
字段。 You can include id
by adding it to the serializer as an attribute like this: 您可以通过将其作为属性添加到序列化程序来包含id
,如下所示:
class FooSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField()
class Meta:
model = Foo
fields = '__all__'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.