Home > Software design >  Django rest framework post request returns 200 but data is not saved in the database
Django rest framework post request returns 200 but data is not saved in the database

Time:10-12

when post request is sent to the api, api returns Ok as the response but no data is inserted into the database.

views.py


@api_view(['POST'])
def createTicketList(request):
    serializer = TicketListSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    else:
        return Response(serializer.errors)

serializer.py


class TicketListSerializer(serializers.ModelSerializer):
    class Meta:
        model = TicketListTable
        fields = '__all__'

    def create(self, validated_data):
        return TicketListTable(**validated_data)

models.py


class TicketListTable(models.Model):
    ticketListName = models.CharField(max_length=50)
    ticketListCreated = models.DateTimeField()
    ticketListUpdates = models.DateTimeField()

    def __str__(self):
        return self.ticketListName

    class Meta:
        app_label = "backend"
        db_table = "TicketListTable"

postman api

postman api post request

CodePudding user response:

Because you don't save TicketeListTable instance in serializer create function. If you remove create function, the instance will be saved. There is already a create function in ModelSerializer.

https://www.cdrf.co/3.12/rest_framework.serializers/ModelSerializer.html#create

  • Related