如何从Django序列化器中列出字段名称

huangapple go评论67阅读模式
英文:

How to list the field names from a Django serializer

问题

我有一个模型序列化器,我想知道如何获取该序列化器字段的名称列表。类似地,我知道如何从模型和表单中获取字段的列表。

示例模型:

class Account(models.Model):
    account_holder = models.CharField(blank=False, max_length=50)
    age = models.IntegerField(blank=False)
    salary = models.DecimalField(blank=False, max_digits=10, decimal_places=2)

然后可以从以下方式获取字段列表:

从模型:

obj_fields = Account._meta.get_fields()  # 作为对象
[field.name for field in Account._meta.get_fields()]  # 作为字符串列表
# 输出: ['id', 'account_holder', 'age', 'salary']

从表单:

class AccountForm(forms.ModelForm):
    class Meta:
        fields = '__all__'
        model = Account

# 表单字段列表(其中一种可能的方法之一,不会偏离主题):
fields = AccountForm.base_fields  # 作为对象字典
[field for field in AccountForm.base_fields.keys()]  # 作为字符串列表
# 输出: ['account_holder', 'age', 'salary']

然后我有一个序列化器:

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            'id',
            'account_holder',
            'age',
            'salary',
            'age_score',
            'salary_score',
        )

这个序列化器比模型有更多的字段。但是,例如使用以下方法,会抛出错误:

>>> AccountSerializer.get_field_names()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: ModelSerializer.get_field_names() missing 3 required positional arguments: 'self', 'declared_fields', and 'info'

显然,我不知道如何使用这个方法,也不知道是否有其他方法。

英文:

I have a model serializer and I was wondering how to get a list of the names of the fields of this serializer. Similarly, I know how to get a list of the fields form a model and from a form.

Example model:

class Account(models.Model):
    account_holder = models.CharField(blank=False, max_length=50)
    age = models.IntegerField(blank=False)
    salary = models.DecimalField(blank=False, max_digits=10, decimal_places=2)

Then the list of fields can be derived from:

obj_fields = Account._meta.get_fields()  # as objects
[field.name for field in Account._meta.get_fields()] # as list of strings
# output: [&#39;id&#39;, &#39;account_holder&#39;, &#39;age&#39;, &#39;salary&#39;]

From the form:

class AccountForm(forms.ModelForm):
    class Meta:
        fields = &#39;__all__&#39;
        model = Account

The list of the form fields (one of the possible methods without derailing into a different topic):

fields = AccountForm.base_fields # as dictionary of objects
[field for field in AccountForm.base_fields.keys()] # as list of strings
# output: [&#39;account_holder&#39;, &#39;age&#39;, &#39;salary&#39;]

And I have a serializer:

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            &#39;id&#39;,
            &#39;account_holder&#39;,
            &#39;age&#39;,
            &#39;salary&#39;,
            &#39;age_score&#39;,
            &#39;salary_score&#39;,
        )

which has a few more fields than the model. But for example using the following, it throws an error:

&gt;&gt;&gt; AccountSerializer.get_field_names()
Traceback (most recent call last):
  File &quot;&lt;console&gt;&quot;, line 1, in &lt;module&gt;
TypeError: ModelSerializer.get_field_names() missing 3 required positional arguments: &#39;self&#39;, &#39;declared_fields&#39;, and &#39;info&#39;

Clearly, I ignore how to use this method and if there is another method.

答案1

得分: 1

你必须在序列化器的实例上调用方法(而不是类本身):

serializer = AccountSerializer()
fields = serializer.get_fields().keys()
英文:

You have to call the methods on an instance of the serializer (not the class itself):

serializer = AccountSerializer()
fields = serializer.get_fields().keys()

答案2

得分: 0

我已经找到了这个使用序列化器类的一行代码,它对我来说运行得很好:

fields = AccountSerializer.Meta.fields # 返回一个字符串元组

作为一点说明:我发现SofienM的方法可以从对象中获取更多信息。

英文:

I have found this one-liner using the serializer class which works fine for me:

fields = AccountSerializer.Meta.fields # return a tuple of strings

As a note: I find the method by SofienM can give more information out of the object.

huangapple
  • 本文由 发表于 2023年7月24日 17:20:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753037.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定