0

my serializer.py file is as

...
class RelativeSerializerSLC(serializers.ModelSerializer):
    full_name = serializers.CharField(source="user.full_name")
    rtl_full_name = serializers.CharField(source="user.rtl_full_name")
    gender = serializers.CharField(source="user.gender")
    phone = serializers.CharField(source="user.phone")
    email = serializers.CharField(source="user.email")
    avatar = serializers.CharField(source="user.avatar")
    date_of_birth = serializers.CharField(source="user.date_of_birth")

    class Meta:
        model = Relative
        fields = ("full_name", "rtl_full_name", "gender", "phone", "email", "avatar", "date_of_birth", "blood_group", "rel")
        read_only_fields = ["patient"]


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "id", "full_name", "rtl_full_name", "gender", "phone", "email", "date_of_birth", "avatar"

there i'm creating other serializer fields(userSerializer) and added to my RelativeSerializer. that seems uglyyy to me, i have no idea on. is there any better option like using one serializer fields for other.

Thanks, new to DRF :)

1 Answer 1

1

Maybe try this:

 class RelativeSerializerSLC(serializers.ModelSerializer):
   users = UserSerializer(read_only=True)
   class Meta: 
      model = Relative
      fields = ("full_name", "rtl_full_name", "gender", "phone", "email", "avatar", 
      "date_of_birth", "blood_group", "rel")
      read_only_fields = ["patient"]

And put UserSerializer class on top of the relativeSerializer. Let me know if it works. I don't see your model fields so it might not be.

Check out for nested serializers here https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.