2

I created the following fieldmodels.py

added_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

and it contained the user Id , but how to make it contain the username instead.

1
  • 1
    You can access username with user_id, Wherever you want to access. Commented Feb 18, 2021 at 8:16

2 Answers 2

2

ForeightKey key always reference with an id.If you want to display the username you can do something like added_by.username

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

1 Comment

my views.py look like this ` class PaperG(APIView): def get(self, request, format=None): # i could try models.added_by.username or request.username but I don't know how to implement that snippets = Post.objects.all() serializer = SerlizePaper(snippets, many=True) return Response(serializer.data) `
1

If you're using Django Rest Framework, then here's your solution:

class Your_Model_Serializer(serializers.ModelSerializer):
added_by = serializers.CharField()
class Meta:
    model = Your_Model_Object
    fields = ['added_by']

Notice the added_by =serializers.Charfield()? That will return the ForeignKey as text not ID.

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.