【问题标题】:DRF setting fields with non string非字符串的 DRF 设置字段
【发布时间】:2017-04-30 18:32:30
【问题描述】:

免得说我们有这样的代码。

class UserProfileDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('userThumbnail', 'point')

我想做的不是使用('userThumbnail', 'point')

但是像这样(nameof(UserProfile.userThumbnail), nameof(UserProfile.point))

所以我不必每次重命名这些字段时都重写这些字段。

我该怎么做?

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    是的,你可以。

    def nameof(field):
        return field.field_name
    
    class User(models.Model):
        git = models.CharField(max_length = 10)
    
    >>> nameof(User.git)
    'git'
    

    【讨论】:

    • AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'field_name' 出现此错误..// 你确定 field_name 在 python3 上工作吗?
    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 2011-01-28
    • 2019-01-20
    • 1970-01-01
    • 2015-05-11
    相关资源
    最近更新 更多