我Django-Rest
的类User
包含字段first_name
,类Account
包含字段username
和a_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)
谢谢
答案 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']