Django:显示用户名而不显示ID,怎么办? [英] Django: Showing username and not ID, how?

查看:79
本文介绍了Django:显示用户名而不显示ID,怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下序列化程序类.

I have the following serializers class.

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('id', 'name', 'active', 'type', 'user')

列出所有配置文件时,用户字段显示用户ID.如何更改它以显示user.username?我知道我的模型只是将其添加到我的元类中,但是没有创建用户模型(它是Django的一部分).在调用用户以显示用户名而不是ID时,我该如何告诉Django?

When listing all profiles the user field shows the user ID. How do I change this to show the user.username? I know with my models I just add this to my meta class, but as did not create the user model (its part of Django). How do I tell Django when calling a user to show the username and not the id?

非常感谢.

推荐答案

两种明显的处理方法:

首先,您可以使用 dotted.notation 强制 user 字段的rel ="noreferrer">源参数 user.username ,而不是默认的 user .

Firstly you can use the dotted.notation to force the source argument of the user field to be user.username instead of the default user.

class ProfileSerializer(serializers.ModelSerializer):
    user = serializers.Field(source='user.username')

    class Meta:
        model = Profile
        fields = ('id', 'name', 'active', 'type', 'user')

请注意, Field 是标准的只读字段,因此您将无法使用此序列化程序来更新用户.

Note that Field is a standard read-only field, so you wouldn't be able to update the user using this serializer.

或者,如果您希望用户成为可写字段,则可以使用

Alternatively, if you want user to be a writable field, you can use a SlugRelatedField like so...

class ProfileSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(slug_field='username')

    class Meta:
        model = Profile
        fields = ('id', 'name', 'active', 'type', 'user')

如果需要,还可以通过将 read_only = True 添加到 SlugField 来使用第二种方法,但是使用只读字段.

If you want you could also use the second approach but use a read-only field, by adding read_only=True to the SlugField.

这篇关于Django:显示用户名而不显示ID,怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆