Search code examples
djangodjango-rest-frameworkdjango-viewsdjango-serializerdjango-rest-auth

How to mark Username with rest-auth in the DRF as a name instead of a number


I am going to use Django to receive the value of Arduino and serialize it into REST API. First of all, member management function was established with rest-auth and 'name' variable was designated as a foreign key to store sensor values for each user by creating an aduinos model. After running the server and logging in, I checked the API that contains the data of each user, and there was a number next to the name, not the user's username. I wonder how to change this to username instead of number. here is my code

models.py

class arduino (models.Model) :
    name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
    temp = models.FloatField()
    humi = models.FloatField()

serializers.py

class arduinoSerializers (serializers.ModelSerializer) :
    class Meta :
        model = arduino
        fields = ('name', 'temp', 'humi')

views.py

class arduinoViewSet (viewsets.ViewSet) :
    def dataSend (self, request) :
        queryset = arduino.objects.all()
        serializer = arduinoSerializers(queryset, many=True)
        return Response(serializer.data)

please help me :(


Solution

  • Take a look of the serializer field argument source

    class arduinoSerializers (serializers.ModelSerializer):
        name = serializers.CharField(source='name.username')
    
        class Meta :
            model = arduino
            fields = ('name', 'temp', 'humi')