如何使用 ModelSerializer 显示所有模型字段?

How to display all model fields with ModelSerializer?

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, which requires you to 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__'

您可以使用 fields = '__all__' 获取所有字段,或者您可以指定是否要返回有限数量的字段。参见 documentation

但是这个 returns 外键字段的 id 值,即您的情况下的 producer。要获取 producer 的所有字段,您还需要为此创建一个序列化程序 class。参见 here

所以你更新后的 serializers.py 应该是:

class ProducerSerializer(ModelSerializer):
    class Meta:
        model = Producer

class CarSerializer(ModelSerializer):
    producer= ProducerSerializer(read_only=True)

    class Meta:
        model = Car
        fields = ('producer', 'color', 'car_model', 'doors', )

如果您希望所有字段都包含在序列化程序中,您可以使用 fields = '__all__':

class CarSerializer(serializer.ModelSerializer):
      class Meta:
           fields = '__all__'
           model = Car

但不推荐这种方式。我们应该始终明确指定所有字段。这是因为它使我们能够控制显示的字段。如果我们不想显示某个字段的数据,我们可以避免显示。

 class CarSerializer(serializer.ModelSerializer):
          class Meta:
               fields = ['name', 'color', 'company', 'price', ]
               model = Car