cedrik cedrik - 6 months ago 12
JSON Question

DRF POST object with FK

First, my models :

class Director(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)

class Movie(models.Model):
title = models.CharField(max_length=150, unique=True)
director = models.ForeignKey(Director, related_name="movies")


I'd like to POST json files to create a director, a director with a movie (in once), or a movie.

So, here are my serializers :

class MovieSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
url = HyperlinkedIdentityField(view_name='movie')
class Meta:
model = Movie
exclude = ('director', ) # edit (solution) this line is the problem. It does not only affect the representation... Just remove that and it's OK


class DirectorSerializer(serializers.ModelSerializer):
movies = MovieSerializer(many=True)

class Meta:
model = Director
fields = '__all__'


def create(self, validated_data):
movies = validated_data.pop('movies')
director = self.Meta.model.objects.create(**validated_data)

for movie in movies:
Movie.objects.create(director=director, **movie)

return director


So, (thanks httpie), to create a new director :

{
"first_name": "Christopher",
"last_name": "Nolan",
"movies": []
}


works fine.
To create a new director with a movie :

{
"first_name": "Luc",
"last_name": "Besson",
"movies": [
{
"title": "Le Grand Bleu"
}
]
}


works too.
But I'm not able to add a new movie i.e. create a new movie.
JSON :

{
"title": "Interstellar",
"director": 1
}


director's id = 1 => C. Nolan ;-)

I think I'm missing something so if anyone could help me, advise me, or anything ?

Thanks, regards

EDIT the question is :



What is the JSON file I have to POST to add "Interstellar" movie to Nolan's movies (id_director=1) ?

Answer

You are not able to add a new movie here because you have excluded the director field in your MovieSerializer. But the director field is required by the Movie model. Removing the exclude should work