ModelSerializer django rest框架中的所有字段 [英] All fields in ModelSerializer django rest framework
问题描述
models.py :
class Car():
producer = models.ForeignKey(Producer, blank=True, null=True,)
color = models.CharField()
car_model = models.CharField()
doors = models.CharField()
serializers.py :
class CarSerializer(ModelSerializer):
class Meta:
model = Car
fields = Car._meta.get_all_field_names()
因此,这里我要使用所有字段。但是我有一个错误:
So, here I want to use all fields. But I have an error:
字段名称 producer_id
对模型汽车
。
Field name producer_id
is not valid for model Car
.
如何解决?
谢谢!
推荐答案
根据有关ModelSerializer的Django REST Framework文档:
默认情况下,该类上的所有模型字段都将映射到相应的序列化器字段。
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
这与 Django的ModelForms 不同。以指定特殊属性'__ all __'
来利用所有模型字段。因此,只需声明模型即可。
This is different than Django's ModelForms, which requires you to specify the special attribute '__all__'
to utilize all model fields. Therefore, all that is necessary is to declare the model.
class CarSerializer(ModelSerializer):
class Meta:
model = Car
更新(对于大于等于3.5的版本)
上述行为在版本3.3中已弃用,自版本3.5起已禁止。
Update (for versions >= 3.5)
The behaviour described above was deprecated in version 3.3, and forbidden since version 3.5.
现在必须使用特殊属性'__ all __'
来使用Django REST Framework中的所有字段,与Django Forms相同:
It is now mandatory to use the special attribute '__all__'
to use all fields in the Django REST Framework, same as Django Forms:
未能设置任何字段或排除,在版本3.3中提出了待处理的弃用警告,而在版本3.4中提出了弃用的警告。现在必须使用它。
Failing to set either fields or exclude raised a pending deprecation warning in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.
所以现在它必须是:
class CarSerializer(ModelSerializer):
class Meta:
model = Car
fields = '__all__'
这篇关于ModelSerializer django rest框架中的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!