[Fixed]-Django custon user model/serializer

1👍

May be you can try something like this.

class FarmerSerializer(serializers.ModelSerializer):
    first_name = serializers.CharField(source='user.first_name')
    last_name = serializers.CharField(source='user.last_name')
    ..
    ..
    class Meta:
        model = Farmer
        fields = ('first_name', 'last_name', 'phone_number', 'email')

the trick is to use the ‘source’ attribute.

0👍

You can modify serializer.data returned by the view:

@api_view(('GET',))
def get_all_farmers_details(request):

    #Fetch all the farmers from database
    results = Farmer.objects.all()
    #Serialize the obtained results
    serializer = FarmerSerializer(results, many=True)

    userDict = serializer.data.pop("user", None)
    if userDict is not None:
        serializer.data['first_name'] = userDict['first_name']
        serializer.data['last_name'] = userDict['last_name']

    return Response(serializer.data)

Leave a comment