Django Rest Framework transforming my APIView into a ModelViewSet

Viewed 35

I have the following model,

class Schema(models.Model):
    week = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(53)])
    users = models.ManyToManyField(MyUser, related_name="users")

    class Meta:
        ordering = ('week',)

The model holds a week number and list of users related to that week number. I have then created an APIView where the GET request fetches all the Schemas (my model), and the POST request does the following, if the week number is not in the database then it simply creates a row in the database for the given week number and the given users.

If the week number is already present in the database then I simply overwrite the users related to that week number with the newly given users, the view looks like this,

class SchemaView(APIView):
    permission_classes = (SchemaPermissions,)

    def get(self, request):
        schemas = Schema.objects.all()
        serializer = SchemaSerializer(schemas, many=True)

        return Response(serializer.data)

    def post(self, request):
        data = request.data
        serializer = SchemaSerializer(data=data)
        if serializer.is_valid():
            input_data = serializer.validated_data
            week = input_data.get('week')
            user_ids = input_data.get('user_ids')
            if Schema.objects.filter(week = week).count() > 0:
                schema = Schema.objects.get(week = week).first()
            else:
                schema = Schema.objects.create(week = week)
            schema.users.set(user_ids)
            schema.save()

            return Response(SchemaSerializer(schema).data, status=status.HTTP_200_OK)
        else:
            return Response(status = status.HTTP_400_BAD_REQUEST)

Now this works as expected, however now comes my problem. This only works for a single "Schema" (my model) on POST. What I want is to be able to both POST a single "Schema" or POST multiple "Schema". So my thought was to change my APIView into a ModelViewSet, then take my current POST method and use that as the create() method. And then somehow implement another method which handles the case where multiple "Schema" are posted.

Would this be an okay way to do it, or is there an easier way to do it from my current point. If so, how would I go about transforming my APIView in to a ModelViewSet with said functions.

I would also need to create a router for my urls, or what?

I am what you call, a beginner at Django and I'm trying to learn, so any help is greatly appreciated!

0 Answers
Related