Search code examples
djangodjango-rest-frameworkdjango-allauth

Django allauth SocialAccount model's "extra_data" field


SocialAccount model has the extra_data field in the table. And this model has a relation with the User table. when I am retrieving the User table, trying to add the SocialAccount into the User but having a problem...

serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User
from allauth.socialaccount.models import SocialAccount

UPDATED

I updated the serializers.py and now I can implement add the extra_data into UserDisplaySerializer.

class SocialAccountExtraDataSerializer(serializers.ModelSerializer):
  class Meta:
    model = SocialAccount
    fields = ["extra_data"]
    depth = 1


class UserDisplaySerializer(serializers.ModelSerializer):
  extra_data_set = serializers.SerializerMethodField()

  class Meta:
    model = User
    fields = ["username", "extra_data_set"]
    depth = 1

  def get_extra_data_set(self, instance):
    extra_data = instance.socialaccount_set.all()[0].extra_data
    return SocialAccountExtraDataSerializer(extra_data, many=True).data

BUT this time extra_data field comes with those empty objects. There are six objects like expected but empty?

enter image description here

How should I insert the SocialAccount's extra_data into User serializer as field smoothly...


Solution

  • I solved the problem by not serializing the data before return.

    def get_extra_data_set(self, instance):
        extra_data = instance.socialaccount_set.all()[0].extra_data
        # below serialize and return the data 
        return SocialAccountExtraDataSerializer(extra_data, many=True).data
    

    Instead of above I just return extra_field directly.

    def get_extra_data(self, instance):
        if instance.is_superuser is not True:
            extra_data = instance.socialaccount_set.all()[0].extra_data
            return extra_data