所以我用Django rest框架创建了一个API。我有一个简单的模型关系,即用户->帖子。用户链接到帖子,因为用户是帖子的作者。我要做的就是在我的rest API中显示与POST相关的用户名。如何从链接为外键的模型中引用其他字段?如果我的用户模型包含用户名,个人资料图片和电子邮件,如何在我的帖子模型中显示这些?
这是我要对模型进行处理的一个示例
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
image = models.ImageField(default='default.mp4', upload_to='video_thumbnails')
videoFile = models.FileField(default='default.mp4', upload_to='videos')
date_posted = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User , #Something to get the username here, on_delete=models.CASCADE)
现在显示
{
"title": "HOLROYD SWIPE ACCESS(CS ROOMS)",
"content": "Yeet",
"image": "http://127.0.0.1:8000/media/video_thumbnails/Screenshot_from_2019-08-03_23-37-50.png",
"videoFile": "http://127.0.0.1:8000/media/videos/Screenshot_from_2019-08-03_23-37-52.png",
"date_posted": "2019-10-22T21:01:07Z",
"user": 1
}
我要做的就是显示用户名,而不是在这种情况下显示的USER ID。
我只是希望它看起来像这样
{
"title": "HOLROYD SWIPE ACCESS(CS ROOMS)",
"content": "Yeet",
"image": "http://127.0.0.1:8000/media/video_thumbnails/Screenshot_from_2019-08-03_23-37-50.png",
"videoFile": "http://127.0.0.1:8000/media/videos/Screenshot_from_2019-08-03_23-37-52.png",
"date_posted": "2019-10-22T21:01:07Z",
"user": "usernameassociatedwithpost"
}
这是我的序列化器
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('title', 'content', 'image', 'videoFile', 'date_posted', 'user' )
这是我的views.py
class VideoList(generics.ListCreateAPIView):
queryset = Video.objects.all()
serializer_class = VideoSerializer
class VideoDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Video.objects.all()
serializer_class = VideoSerializer
如果需要更多代码来回答此问题,请告诉我。谢谢!
答案 0 :(得分:0)
您可以使用SlugRelatedField:
class PostSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(slug_field="username", queryset=User.objects.all())
class Meta:
model = Post
fields = ('title', 'content', 'image', 'videoFile', 'date_posted', 'user' )