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()
所以,我想在这里使用所有字段。但我有一个错误:
字段名称 producer_id
对模型 Car
无效。
如何解决这个问题?
谢谢!
最佳答案
根据Django REST Framework's Documentation on ModelSerializers :
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
这与 Django's ModelForms 不同,这需要您 specify the special attribute '__all__'
利用所有模型字段。因此,只需声明模型即可。
class CarSerializer(ModelSerializer):
class Meta:
model = Car
更新(版本 >= 3.5)
上述行为在 3.3 版中已被弃用,自 3.5 版起被禁止。
It is now mandatory使用特殊属性 '__all__'
使用 Django REST Framework 中的所有字段,与 Django Forms 相同:
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__'
关于python - 如何使用 ModelSerializer 显示所有模型字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274591/