Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django access nested object field in serializer

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

like image 294
Boris Le Méec Avatar asked Oct 24 '25 14:10

Boris Le Méec


1 Answers

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']
like image 68
slider Avatar answered Oct 27 '25 04:10

slider