Ali Husham
Ali Husham

Reputation: 936

how to create ForeignKey for username (not userid) in django models.py

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.

Upvotes: 2

Views: 830

Answers (2)

Kolo Safo
Kolo Safo

Reputation: 91

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.

Upvotes: 1

Kenneth Githambo
Kenneth Githambo

Reputation: 177

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

Upvotes: 2

Related Questions