如何在DRF中使用一个请求创建多个对象(相关)?

时间:2015-02-09 22:37:35

标签: python django django-rest-framework

我有一个代表一个Job的类,一个代表一个Tag的类,它描述一个Job,然后我有一个类在它们之间建立一个关系(联结表),所以一个Job可以用多个标签描述:

class JobTag(models.Model):
    job = models.ForeignKey(Job, unique=False, related_name='jobtags')
    tag = models.ForeignKey(Tag, unique=False, related_name='Tag_For_Job')

    created_time = models.DateTimeField(auto_now_add = True)
    modified_time = models.DateTimeField(auto_now = True)

    class Meta:
        unique_together = ('job', 'tag',)

    def __unicode__(self):
        return 'Tag '+self.tag.name +' for job '+ self.job.name

然后我有序列化器:

class TagSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Tag
        fields = ('url','name','badge_pic')
        read_only_fields = ('name','badge_pic')

class JobTagSerializer(serializers.HyperlinkedModelSerializer):
    tag = TagSerializer()
    class Meta:
        model = JobTag
        fields = ('tag',)
        depth=1

class JobSerializer(serializers.HyperlinkedModelSerializer):
    jobtags=JobTagSerializer(many=True)
    class Meta:
        model = Job
        fields = ('url','name', 'employer','jobtags','description')
        read_only_fields = ('employer',)

因此GET请求的http响应是:

{
        "url": "http://127.0.0.1:8000/api/jobs/2/",
        "name": "Odprac mi sneh",
        "employer": "http://127.0.0.1:8000/api/users/4/",
        "jobtags": [
            {
                "tag": {
                    "url": "http://127.0.0.1:8000/api/tags/2/",
                    "name": "Odhadzovanie snehu",
                    "badge_pic": "http://127.0.0.1:8000/media/pictures/tags/0005.jpg"
                }
            }
        ],
        "description": "blablabla"
    }

我的问题非常明显,我如何创建一个作业实例并使用一个POST http请求将相关的JobTags保存在其中?

我尝试重复此方法http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations

class JobSerializer(serializers.HyperlinkedModelSerializer):
        jobtags=JobTagSerializer(many=True)
        class Meta:
            model = Job
            fields = ('url','name', 'employer','jobtags','description')
            read_only_fields = ('employer',)
        def create(self, validated_data):
            jobtag_data = validated_data.pop('jobtags')
            job = Job.objects.create(**validated_data)
            JobTag.objects.create(job=job, **jobtag_data)
            return job

但它返回"在**之后的create()参数必须是映射,而不是列表"错误,那么request.data json应该是什么样的?

或者这种方法不能在我的情况下使用,我应该做一些完全不同的事情吗?

我将不胜感激任何帮助。

修改

如果我尝试访问该列表:

def create(self, validated_data):
        jobtag_data = validated_data.pop('jobtags')
        job = Job.objects.create(**validated_data)
        JobTag.objects.create(job=job, **jobtag_data[0])
        return job

我生成另一个错误:"无法分配" OrderedDict()":" JobTag.tag"必须是"标签" 。实例#&34; 所以我猜我发布的json格式错误了吗?我尝试以这种方式发布数据:

{
        "name": "Odprac mi sneh",
        "jobtags": [
            {
                "tag": {
                    "url": "http://127.0.0.1:8000/api/tags/2/"
                }
            }
        ],
        "description": "veela sneu nemam ruky makam makam makamam",           
    }

2 个答案:

答案 0 :(得分:2)

如果有其他人正面对这个,我想出了最合适的解决方案,以便在创建对象并使用嵌套序列化作为输出时使用了jobtags的超链接序列化:

我为每种情况编写了序列化程序,用于序列化发送给客户端的数据:

class JobTagNestedSerializer(serializers.HyperlinkedModelSerializer):
    tag = TagSerializer()
    class Meta:
        model = JobTag
        fields = ('tag',)
        depth=1



class JobNestedSerializer(serializers.HyperlinkedModelSerializer):
    jobtags=JobTagNestedSerializer(many=True,read_only=True)
    class Meta:
        model = Job
        fields = ('url','name', 'employer','jobtags','description')
        read_only_fields = ('employer',)

并且用于创建新Job,因此对于从客户端发送到DRF的数据:

class JobTagSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = JobTag
            fields = ('tag',)

class JobCreateSerializer(serializers.HyperlinkedModelSerializer):
        jobtags=JobTagSerializer(many=True,required=False)
        class Meta:
            model = Job
            fields = ('url','name', 'employer','jobtags','description')
            read_only_fields = ('employer',)

        def create(self, validated_data):
            tag_data = validated_data.pop('jobtags')
            job = Job.objects.create(**validated_data)
            for tag in tag_data:
                d=dict(tag)
                JobTag.objects.create(job=job, tag_id=d['tag'].pk)
            return job

因此,DRF希望客户端的POST json看起来像:

{
        "name": "Odprac mi sneh",
        "employer": "http://127.0.0.1:8000/api/users/4/",
        "jobtags": [
            {
                "tag": "http://127.0.0.1:8000/api/tags/2/"
            },
            {
                "tag": "http://127.0.0.1:8000/api/tags/5/"
            }
        ],
        "description": "veela sneu nemam ruky makam makam makamam"
    }

答案 1 :(得分:1)

我相信你应该提供POST数据中每个标记的id而不是url,如下所示:

{
    "name": "Odprac mi sneh",
    "tags": [
        {
            "id": 2
        },
        {
            "id": 3
        }
    ],
    "description": "veela sneu nemam ruky makam makam makamam"
}

然后,在您的create方法中,您应该能够遍历标记:

def create(self, validated_data):
    tag_data = validated_data.pop('tags')
    job = Job.objects.create(**validated_data)

    for tag in tag_data:
        JobTag.objects.create(job=job, tag_id=tag["id"])

    return job