如何将外键添加到用户名中.Django REST框架



在序列化过程中,我注意到Post模型的post_author外键引用了创建者的id,因此,我无法在REST API中显示创建者的用户名,只能显示post_author id。当我在前端获取数据时,我如何添加post_creator的用户名,以便其他用户可以读取它?

models.py//CustomUser=帖子的创建者。

class CustomUser(AbstractUser):
fav_color = models.CharField(blank=True, max_length=120)
class Post(models.Model):
post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts')
post_title = models.CharField(max_length=200)
post_body = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.post_title

视图.py

@api_view(['GET'])
def post_list(request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)

序列化程序.py用户模型和模型后序列化

class CustomUserSerializer(serializers.ModelSerializer):
"""
Currently unused in preference of the below.
"""
email = serializers.EmailField(required=True)
username = serializers.CharField()
password = serializers.CharField(min_length=8, write_only=True)
class Meta:
model = CustomUser
fields = ('email', 'username', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password', None)
# as long as the fields are the same, we can just use this
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'

API的单个帖子

{
"id": 1,
"post_title": "first_post",
"post_body": "qwe1",
"created_date": "2020-11-17T19:30:55Z",
"published_date": null,
"post_author": 1
},

您需要重写序列化程序:

class PostSerializer(serializers.ModelSerializer):
post_author_username = serializers.ReadOnlyField(source="post_author.username")
class Meta:
model = Post
fields = [post_author_username, post_title, post_body, created_data, published_data]

您可以在PostSerializer:中指定post_author序列化程序

class PostSerializer(serializers.ModelSerializer):
post_author=CustomUserSerializer(read_only=True)

class Meta:
model = Post
fields = '__all__'

你可以在这里看到文件

最新更新