Home > Blockchain >  DRF: Updating a model in another models serializer or view
DRF: Updating a model in another models serializer or view

Time:02-12

so I have a User and schools model which are related as an Owens(ManyToMany), student, and staff, if an owner registers and creates a school, I would like to perform a partial update to the Owens field of the request.user from having a null/blank or previously created schools to adding the newly created school

user model

 class User(AbstractBaseUser, PermissionsMixin):
    
        class SEX(models.TextChoices):
            ...
    
        class TYPES(models.TextChoices):
            ...
    
        ...
        owens = models.ManyToManyField(School, verbose_name=_(
            "School_owner"), related_name='Schoolowner', blank=True)

serializers.py

class SchoolSerializerBase(serializers.ModelSerializer):
    ...

class Meta:
    model = School
    fields = ...

def validate(self, attrs):
     ...
    return attrs

def create(self, validated_data):
    instance = School.objects.create(
        ...
    )
    instance.save()
    return instance

and i have a simple view for it

class CreateSchoolView(generics.CreateAPIView):
    queryset = School.objects.all()
    permission_classes = [IsSchoolOwner, ]
    serializer_class = SchoolSerializerBase

My question: how do I update the request.user.ownes field and add the school instance to it??

CodePudding user response:

You can obtain that result by overriding .create() in your serializer

In your serializer

def create(self, validated_data):
   instance = super().create(validated_data) # this is the school
   # you then create the entry for your User School
   # example
   user = self.context['request'].user
   user.owens.add(instance)
   return instance

https://docs.djangoproject.com/en/3.2/ref/models/relations/

  • Related