How to add a foreign key to the username. Django REST framework

During serialization, i noticed that the post_author Foreign Key of the Post model is referencing the id of the creator and thus, i can't display the username of the creator in the REST API, only the post_author id. How can i add the username of the post_creator, so that it is readable to other users, when i fetch the data on the frontend?

models.py // CustomUser = the Creator of the post.

class CustomUser(AbstractUser):
    fav_color = models.CharField(blank=True, max_length=120)

class Post(models.Model):
    post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts')
    post_title = models.CharField(max_length=200)
    post_body = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.post_title

views.py

@api_view(['GET'])
def post_list(request):
    posts = Post.objects.all()
    serializer = PostSerializer(posts, many=True)
    return Response(serializer.data)

serializers.py user model and post model serialization

class CustomUserSerializer(serializers.ModelSerializer):
    """
    Currently unused in preference of the below.
    """
    email = serializers.EmailField(required=True)
    username = serializers.CharField()
    password = serializers.CharField(min_length=8, write_only=True)

    class Meta:
        model = CustomUser
        fields = ('email', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        # as long as the fields are the same, we can just use this
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

single post from the API

{
    "id": 1,
    "post_title": "first_post",
    "post_body": "qwe1",
    "created_date": "2020-11-17T19:30:55Z",
    "published_date": null,
    "post_author": 1
},


Read more here: https://stackoverflow.com/questions/64895995/how-to-add-a-foreign-key-to-the-username-django-rest-framework

Content Attribution

This content was originally published by gonzo8874 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: