Django Rest Framework相关领域

时间:2018-05-24 10:52:49

标签: django django-rest-framework

我是Django的新手我希望从另一个模型中获得个人资料图片 主题

models.py

class UserProfile(models.Model):
    user  = models.OneToOneField(User)
    file  = models.ImageField(upload_to='profile_image', blank=True)
    def __unicode__(self):
        return u'%s' % self.user

class Topics(models.Model):
    user  = models.ForeignKey(User)
    title = models.charField(max_length = 55)

serializers.py

User = get_user_model()

class pic(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ['file']

class UserInfo(serializers.ModelSerializer):
    username = pic(read_only=True)
    class Meta:
        model = User
        fields = ['username','first_name',]

class TopicSerializer(serializers.ModelSerializer):
    user= UserInfo(read_only=True)
    class Meta:
        model=Topics
        fields = ('user','title',)

我是这样的:

"user": {
    "username": {},
    "first_name": ""
},
"title": "Django the title",

现在我需要与主题字段相关的每个文件字段以及用户的名字电子邮件

我想要这样:

"user": {
    "username": "akash",
    "first_name": "Akash DK"
    "file":"static/imag.png"
},
"title": "Django the title",

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以在SerializerMethodField序列化程序中使用UserInfo查找配置文件图像并将其添加到输出数据中。

class UserInfo(serializers.ModelSerializer):
    file = serializers.SerializerMethodField()

    def get_file(self, user):
        return UserProfile.objects.get(user=user).file.url

    class Meta:
        model = User
        fields = ['username','first_name', 'file']