如何在Django Rest Framework中为多个模型使用模型字段

时间:2016-01-12 21:20:03

标签: django django-rest-framework

我有一个模型 BstUserActionLog ,带有Django模型用户的外键。我有另一个用户个人资料信息模型, BstUserProfile 。当我使用ModelSerializer序列化 BstUserActionLog 时,我确实将Django 用户信息序列化了。但我还需要使用与用户模型相同的user_id来序列化 BstUserProfile

如何序列化 BstUserActionLog ,模型用户 BstUserProfile 都被序列化?

来自我的models.py:

class BstUserActionLog(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    bst_action_type = models.ForeignKey(BstActionType)
    action_date = models.DateTimeField(auto_now_add=True)
    bst_book = models.ForeignKey(BstBook)
    new_value_id = models.IntegerField(blank=True, null=True)
    old_value_id = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'bst_user_action_log'

class BstUserProfile(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, unique=True)
    website = models.CharField(max_length=200)
    picture = models.CharField(max_length=100)
    is_avatar_uploaded = models.BooleanField(default=False)
    is_cover_uploaded = models.BooleanField(default=False)

    class Meta:
        managed = False
        db_table = 'bst_user_profile'
        app_label = 'bst'   

来自我的serializers.py:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','username',)

class BstUserActionLogSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = BstUserActionLog
        fields = ('id', 'user', 'bst_action_type', 'action_date', 'bst_book', 'new_value_id', 'old_value_id')
        depth = 3

1 个答案:

答案 0 :(得分:3)

我的解决方案的关键是SerializerMethodField。通过这个,可以添加一个用方法计算的新字段。此方法签名包含要序列化的对象。之后,使用常规方法序列化程序返回序列化对象。

来自我的serializers.py

class BstUserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = BstUserProfile
        fields = ('is_avatar_uploaded', 'is_cover_uploaded')

class BstUserActionLogSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    user_profile = serializers.SerializerMethodField()

    def get_user_profile(self, obj):
        try:
            user_profile = BstUserProfile.objects.get(user_id=obj.user_id)
            return BstUserProfileSerializer(user_profile).data
        except Exception as e:
            return {}

    class Meta:
        model = BstUserActionLog
        fields = ('id', 'user', 'user_profile', 'bst_action_type', 'action_date', 'bst_book', 'new_value_id', 'old_value_id')
        depth = 3