Django Rest通过id更新了许多 [英] Django Rest update many to many by id

查看:58
本文介绍了Django Rest通过id更新了许多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python和django rest的新手。但是我很困惑。在Django Rest框架中更新多对多关系的最佳方法是什么。
我阅读了文档
http://www.django-rest-framework.org/api-guide/relations/#manytomanyfields-with-a-through-model
默认情况下,以

I'm novice in python and django rest. But I'm confused. What is the best way to update many to many relation in django rest framework. I read the docs http://www.django-rest-framework.org/api-guide/relations/#manytomanyfields-with-a-through-model By default, relational fields that target a ManyToManyField with a through model specified are set to read-only.

如果您明确指定指向带有直通模型的ManyToManyField的关系字段,请确保将read_only设置为是的。

If you explicitly specify a relational field pointing to a ManyToManyField with a through model, be sure to set read_only to True.

所以,如果我有代码

class Master(models.Model):
    # other fields  
    skills = models.ManyToManyField(Skill)

class MasterSerializer(serializers.ModelSerializer):
    skills = SkillSerializer(many=True, read_only=False)

这将返回技能作为对象列表。而且我没有办法更新它们。据我了解,在M2M方面,Django倾向于使用对象而不是对象ID。如果我使用yii或rails,我将使用直通模型。我想获取skill_ids字段。我可以读写。我可以执行写操作

This will return skills as list of objects. And I don't have a way to update them. As far as I understood Django prefers work with objects vs object id when it comes to M2M. If I work with yii or rails I will work with "through" models. I would like to get skill_ids field. That I could read and write. And I can do this for write operation

class MasterSerializer(serializers.ModelSerializer):
    skill_ids = serializers.ListField(write_only=True)

    def update(self, instance, validated_data):

    # ...
    validated_data['skill_ids'] = filter(None, validated_data['skill_ids'])
    for skill_id in validated_data['skill_ids']:
        skill = Skill.objects.get(pk=skill_id)
        instance.skills.add(skill)

    return instance

但是我不能让它在字段中返回skill_ids。并进行读写操作。

But I cannot make it return skill_ids in field. And work for read and write operations.

推荐答案

一些注意事项。

首先,你不知道在您的示例中不是显式的穿透表。因此,您可以跳过这一部分。

First, you don't an explicit through table in your example. Therefore you can skip that part.

第二个是您正在尝试使用嵌套的序列化器,它们比您要实现的复杂得多。

Second is you are trying to use nested serializers which are far more complex than what you're trying to achieve.

您可以使用PrimaryKeyRelatedField来简单地读取/写入相关ID:

You can simply read/write related id by using a PrimaryKeyRelatedField:

class MasterSerializer(serializers.ModelSerializer):
    skills_ids = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=Skill.objects.all(), source='skills')

应该能够读/写:

{id: 123, first_name: "John", "skill_ids": [1, 2, 3]}

请注意,从JSON的 skill_ids到模型的技能的映射是通过使用可选参数source

Note that the mapping from JSON's "skill_ids" to model's "skills" is done by using the optional argument source

这篇关于Django Rest通过id更新了许多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆