POST请求Django多对多模型的错误

时间:2016-10-11 15:52:14

标签: django django-models django-rest-framework

我在尝试发出POST请求以在sqlite3数据库中创建特定模型时收到以下错误:

"<Article>" needs to have a value for field "article" before this many-to-many relationship can be used.

我正在使用Django REST Framework构建REST API,我有两个具有多对多关系的模型,如下所示:

class Publication(models.Model):
    title = models.CharField(max_length=30)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

文章的views.py中的相应摘录如下:

class ArticleList(mixins.ListModelMixin, mixins.CreateModelMixin):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

我假设问题是在POST请求完成之前文章没有保存,因为我能够使用Django的数据库API执行所有CRUD操作。

PublicationSerializer如下:

class PublicationSerializer(serializers.Serializer):
    pk = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=True, max_length=120, allow_blank=False)


def update(self, instance, validated_data):
    instance.title = validated_data.get('title', instance.title)
    instance.save()
    return instance

def create(self, validated_data):
    return Publication.objects.create(**validated_data)

ArticleSerializer如下:

class ArticleSerializer(serializers.Serializer):
    pk = serializers.IntegerField(read_only=True)
    headline = serializers.CharField(required=True, max_length=120, allow_blank=False)
    publications = serializers.StringRelatedField(many=True)

def update(self, instance, validated_data):
    instance.headline = validated_data.get('headline', instance.headline)
    instance.publications = validated_data.get('publications', instance.publications)
    instance.save()
    return instance

def create(self, validated_data):
    return Article.objects.create(**validated_data)

我试图发布的数据样本:

{
"headline": "Trending Topics",
"publications": []
}

解决此问题的最佳方法是什么?

0 个答案:

没有答案