I'm doing a little tutorial on Django Rest Framework, as I never used it before even though I have some experience with Django using templates.

So I'm diverging a little from the tutorial class as I think I learn better this way, so I got to a point where in a Movie Rating simple application, when you do a GET from the Ratings serializer, you get just the FK IDs and the "stars" rating I added:

[
    {
        "id": 1,
        "user": 1,
        "movie": 1,
        "stars": 5
    },
    {
        "id": 2,
        "user": 1,
        "movie": 4,
        "stars": 4
    }
]

As I learned in a previous lesson from the said course, I know you can specify a serializer for each field, so instead on a GET request you get the dictionary with the whole data.

class RatingSerializer(serializers.ModelSerializer):
    movie = MovieSerializer(many=False)
    user = UserSerializer(many=False)

    class Meta:
        model = Rating
        fields = ('id', 'user', 'movie', 'stars')

That way the return from the GET to the Ratings route shows relational data instead of only the IDs:

[
    {
        "id": 1,
        "user": {
            "id": 1,
            "username": "admin",
            "email": "[email protected]"
        },
        "movie": {
            "id": 1,
            "title": "Matrix 2",
            "synopsis": "Neo is back."
        },
        "stars": 5
    },
    {
        "id": 2,
        "user": {
            "id": 1,
            "username": "admin",
            "email": "[email protected]"
        },
        "movie": {
            "id": 4,
            "title": "Jurassic Park",
            "synopsis": "Big chickens."
        },
        "stars": 4
    }
]

But now when I try to add a new Rating using a POST request, when using a form-data on Postman it says the fields are required even though I'm passing them already, and when I try to send a POST using a JSON format it returns telling me that I can't pass only the IDs, that I need to pass a whole dictionary for "movie" and "user" fields.

POST
http://127.0.0.1:8000/api/v1/ratings/
movie:4
stars:4
user:1

I researched a little about it and saw an answer saying to override the "create", and I tried adding this to my Serializer class (the one from the previous code snippet), but to no effect. Still getting the same errors refusing to accept only the IDs

def create(self, validated_data):
    id_movie = validated_data.pop('movies')
    id_user = validated_data.pop('users')
    movie = Movie.objects.get(id=id_movie)[0]
    user = User.objects.get(id=id_user)[0]

    return Rating

What do I need to do the be able to POST only passing the IDs, instead of the whole data for each field? Redefining the "create" is the correct way and I am missing something in my code? Or this is the wrong way to do it?

Thanks in advance.

🔴 No definitive solution yet