I Django-Rest have a class User that contain the field first_name, and a class Account that contain the fields username and a_class_ref that is a one-to-one' relation.
How it is possible in the serializer of B to do something like :
class AccountSerializer():
class Meta:
model= Account
fields= [
'username',
'firstname`
]
Account :
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
And User is the extended AbstractUser from Django-rest-framework, that comes with a first_name = models.CharField(_('first name'), max_length=30, blank=True)
Thank you
You can declare a custom field with the source attribute:
class BSerializer(serializers.ModelSerializer):
a_field = serializers.CharField(source='a_class_ref.a_field')
class Meta:
model= B
fields= ['b_field', 'a_field']
Edit
Based on the models you posted, the following should work:
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With