带FK的DRF POST对象

时间:2016-05-31 10:06:02

标签: python json django django-rest-framework

首先,我的模型

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")

我想发布json文件来创建导演,带电影的导演(一次性)或电影。

所以,这是我的序列化程序

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

所以,(感谢httpie),创建一个新导演:

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

工作正常。 用电影创建新导演:

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

也有效。 但我无法添加新电影 创建新电影。 JSON:

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

导演的id = 1 => C. Nolan; - )

我想我错过了什么,所以如果有人可以帮助我,建议我或其他什么?

谢谢,问候

编辑问题是:

我必须POST的JSON文件才能将“Interstellar”电影添加到Nolan的电影中(id_director = 1)?

1 个答案:

答案 0 :(得分:3)

您无法在此处添加新电影,因为您已排除MovieSerializer中的director字段。但导演领域是电影模型所必需的。删除排除应该工作