Home > OS >  Django get the current email of the user by default in a different serializer based on the selected
Django get the current email of the user by default in a different serializer based on the selected

Time:07-01

I was wondering what the correct way is to get the current email of the user by default in a different serializer based on the selected "userid". I have tried many examples from the DRF serializer

CodePudding user response:

You can use SerializerMethodField. It will allow you to create a custom field in the serializer. By default SerializerMethodField looks for a method get_<field name>, and performs the according logic:

from users.models import NewUser


class AlertsSerializer(serializers.ModelSerializer):
    ...
    email = serializers.SerializerMethodField()

    class Meta:
        model = SectionAlerts
        fields = "__all__"

    def get_email(self, obj):
        user_id = self.initial_data['userid']  # get the `userid` from the request body
        user = NewUser.objects.get(pk=user_id)  # fetch the user from DB
        return UserlistSerializer(instance=user).data

CodePudding user response:

You don't show the NewUser model so not sure exactly what field you need, but you can use dot notation for the source of a serializer field.

From DRF docs:

The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email').

See this section of the docs: https://www.django-rest-framework.org/api-guide/fields/#core-arguments

  • Related