gpt4 book ai didi

python - 带 FK 的 DRF POST 对象

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:59 24 4
gpt4 key购买 nike

首先,我的模型:

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
}

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

我想我遗漏了一些东西,所以如果有人可以帮助我、给我建议或其他什么?

谢谢,问候

编辑问题是:

要将“星际穿越”电影添加到 Nolan 的电影 (id_director=1),我必须 POST 什么 JSON 文件?

最佳答案

您无法在此处添加新电影,因为您已在 MovieSerializer 中排除了 director 字段。但是电影模型需要 director 字段。删除排除应该有效

关于python - 带 FK 的 DRF POST 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37542700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com