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

How to get object_set in serializer from Many to Many?

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

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

所以,person_field只有在班级才能得救。

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

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

因为Group和Classe是ManyToManyfield;因此,一个组可以有多个类,一个类可以有多个组。

因此要获取一组类的列表:

classes = list(mygroup.classe_set.all())

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

# first get all the associated Classe, you need the '.all()'
# keep in mind that .all() gives you a queryset
classes = instance.classe_set.all()
for c in classes:
    students = c.persons.all() # persons of a classe of this group
    if students.filter(id=person_field.id).exists():
        # if this person is in the persons of this classe of this group
        # then we add this person to this group
        instance.persons.add(person_field)
        break # we only need to add it once, right? 

希望对您有所帮助!