1

I need help. My API get me "id": null instead of the uuid given in mongoDB.

Here's the results :

Result in RestER

Result in NoSqlManager

And Here's my code :

serializers.py

from rest_framework import serializers
from testapp.models import Test

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test
        fields=fields='__all__'

models.py

from django.db import models

class Test(models.Model):
    testChar = models.CharField(max_length=255)
    testTwo = models.CharField(max_length=255)

views.py

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse


# Create your views here.
from testapp.models import Test
from testapp.serializers import TestSerializer


@csrf_exempt
def testApi(request,id=0):
    if request.method == 'GET':
        test = Test.objects.all()
        test_serializer = TestSerializer(test,many=True)
        return JsonResponse(test_serializer.data,safe=False)
    elif request.method == 'POST':
        test_data = JSONParser().parse(request)
        test_serializer = TestSerializer(data=test_data)
        if test_serializer.is_valid():
            test_serializer.save()
            return JsonResponse("Added successfully", safe=False)
        return JsonResponse("Failed to Add",safe=False)
    elif request.method == 'PUT':
        test_data=JSONParser().parse(request)
        test=Test.objects.get(TestId=test_data['TestId'])
        test_serializer = TestSerializer(test,data=test_data)
        if test_serializer.is_valid():
            test_serializer.save()
            return JsonResponse("Update successfully", safe=False)
        return JsonResponse("Failed to Update")
    elif request.method == 'DELETE':
        test=Test.objects.get(TestId=id)
        test.delete()
        return JsonResponse("Deleted successfully", safe=False)
General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

0
#at serializers.py use djongo instead of django.db b/c you alredy use djongo and 
add "_id = models.ObjectIdField(primary_key=True)" field. like this

from djongo import models
class Test(models.Model):
    _id = models.ObjectIdField(primary_key=True)
    testChar = models.CharField(max_length=255)
    testTwo = models.CharField(max_length=255)
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 03 '23 at 06:55