Django访问序列化程序中的嵌套对象字段

时间:2018-11-16 19:16:14

标签: python django django-rest-framework

Django-Rest的类User包含字段first_name,类Account包含字段usernamea_class_ref那是one-to-one'关系。

如何在B的序列化程序中执行类似的操作:

class AccountSerializer():
    class Meta:
        model= Account
        fields= [
          'username',
          'firstname` 
        ]

帐户:

class Account(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        related_name='account',
        on_delete=models.CASCADE
    )
    def username(self):
        return self.user.username <== this is the solution that I'm trying to avoid 

User是Django-rest-framework的扩展AbstractUser,带有first_name = models.CharField(_('first name'), max_length=30, blank=True)

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用source属性声明自定义字段:

class BSerializer(serializers.ModelSerializer):
    a_field = serializers.CharField(source='a_class_ref.a_field')

    class Meta:
        model= B
        fields= ['b_field', 'a_field']

修改

根据您发布的模型,以下方法应该起作用:

class Account(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        related_name='account',
        on_delete=models.CASCADE
    )

class AccountSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    firstname = serializers.CharField(source='user.first_name')

    class Meta:
        model= Account
        fields= ['username', 'firstname']