Django REST API ManyToMany更新

时间:2019-03-15 05:56:53

标签: python django rest django-rest-framework many-to-many

我在更新舞台和设备之间的多对多关系的查找表时遇到问题。我还没有找到解决问题的方法,但是我不知道如何正确地描述它,如果创建重复的问题,抱歉。

这就是我所拥有的(简而言之):

# models.py

class Parent(models.Model):
    # other fields
    name = models.CharField(max_length=255)

class Stage(models.Model):
    # other fields
    parent = models.ForeignKey('Parent', related_name='stage', on_delete=models.CASCADE)
    desc = models.CharField(max_length=255)
    device = models.ManyToManyField('Device', related_name='stg', blank=True)

class Device(models.Model):
    # other fields
    name = models.CharField(max_length=255)

# serializer

class ParentSerializer(serializers.ModelSerializer):
    stages = serializers.SerializerMethodField()

    class Meta:
        model = Parent
        fields = '__all__'
        depth = 1

def get_stages(self, obj):
    stg = Stage.objects.filter(parent=obj.id)
    return StageSerializer(stg, many=True).data


# view.py
# In ParentCreate or ParentUpdate I try to update Stage manually

class ParentListCreate(generics.ListCreateAPIView):
    serializer_class = ParentSerializer
    model = Parent
    queryset = Experiment.objects.all()


    #after the Parent created we add new relationship between stage and device

    def create(self, request, *args, **kwargs):
         # after parent created I try to save existing Stage.
         stage = request.data.get('stage', None)
         stg = Stage.objects.get(id=stage["id"])
         stg.name = stage["desc"]
         stg.parent_id = parent_id
         stg.save()
         stg.device.add(Device.objects.get(id=s["device"]))

所以我尝试在views.py中创建Parent时更新Stage-Device关系。它确实在设备和舞台之间建立了联系,但是我的问题是,它不断向Django生成的stage_device表中添加新行。

如何确保我更新旧的stage_device行而不是每次都创建一个新行?

任何输入表示赞赏!

0 个答案:

没有答案