如何从多对多序列化器中获取object_set?

问题描述 投票:0回答:1

我只允许在响应某些语句时保存某些特定字段。让我解释一下。

models.py

class classe(models.Model):
   name = models.CharField(max_length=191)
   groups = models.ManyToManyField('Group')
   persons = models.ManyToManyField('Person')

class Group(models.Model):
   name = models.CharField(max_length=191)
   persons = models.ManyToManyField('Person')

class Person:
   name = models.CharField(max_length=191)

serializers.py

class GroupSerializer(serializers.ModelSerializer):
    persons = PersonSerializer(many=True, read_only=True)
    person_id = serializers.PrimaryKeyRekatedField(queryset=Person.objects.all(), write_only=True)

    def update(self, instance, validated_data, **kwargs):
        instance.name = validated_data.get('name', instance.name)
        person_field = validated_data.get('person_id)
        classe = instance.classe_set #This one doesn't work
        person_classe = classe.persons.all() #This one too
        if (person_field in person_classe):
            instance.persons.add(person_field)
        instance.save()
        return instance

所以,只有当人在实际的classe中时,才能保存person_field

一切正常,但是两行注释不起作用,因此无法访问if语句。

有人知道我该如何解决吗?

python django django-rest-framework django-serializer
1个回答
0
投票

因为组和类彼此之间有许多场,所以一个组可以有多个类,而一个类可以具有许多组。

在您的更新功能中,如果某人属于与该组关联的类中,我猜您正在尝试将该人添加到该组中。如果是,这是您需要的:

# first get the associated Classe, you need the .all()
classes = instance.classe_set.all()
for c in classes:
    students = c.students.all()
    if students.filter(id=person_field).exists():
        instance.persons.add(person)
        break
© www.soinside.com 2019 - 2024. All rights reserved.