How to Access object_set from Many to Many serializer

I want to allow saving some specific field only if it responds to some statement. Let me explain.

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

So, the person_field can be saved only if the person is in the actual classe.

Everything work fine, but the two commented lines don’t, so can’t access the if statement.

Does someone know how can I figure it out ?

Couple things (that might be copy/paste errors, so I’m not sure if there’s something actually wrong here).

  • class Person - isn’t defined as inheriting from Model.

  • classe = instance.classe_set - should probably be classe = instance.classe_set.all()

  • person_classe = classe.persons.all() isn’t going to work because the object classe defined in the previous statement isn’t a single item, it’s a collection of items.

Your model is defined as having a many-to-many relationship between Group and classe; your instance in your update method appears to be a Group; but you’re saying that "the person_field can be saved only if the person is in the actual classe.
Which classe? Any classe associated with that group?

Also, I’d like to add that I strongly suggest you don’t name any model Group. That’s the name of Django’s built-in group model, and any time I’ve tried to use that for myself, I end up with some type of really awkward conflict between the two that causes problems.

I finally figured this out with a loop. Thanks though