I am following this tutorial for using MongoDB and Django with djongo. I am having an error creating the items of this model, but I am following the tutorial closely and I don´t really know what´s the problem. I show here the code from the models, the views and the serializer:
class Piso(models.Model):
nombre = models.CharField(max_length=30,blank=False,default='');
habitantes = models.CharField(max_length=202,blank=False,default='');
class PisoSerializer(serializers.ModelSerializer):
class Meta:
model = Piso
fields = ('id','nombre','habitantes')
And the view method:
@api_view(['POST','GET'])
def piso_list(request):
# GET list of tutorials, POST a new tutorial, DELETE all tutorials
if request.method == 'POST':
piso_serializer = PisoSerializer(data=request.data)
if piso_serializer.is_valid():
piso_serializer.save();#This is the object I fill
return JsonResponse(piso_serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(piso_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'GET':
pisos = Piso.objects.all()
name = request.GET.get('name', None)
if name is not None:
pisos = pisos.filter(nombre__icontains=name)
pisos_serializer = PisoSerializer(pisos, many=True)
return JsonResponse(pisos_serializer.data[0], safe=False)
# 'safe=False' for objects serialization
The problem is that the object does not save the id column of my object in the database, which is created automatically. This is the object the MongoDB saves:
{
"_id": {
"$oid": "5edd1014b9ca43bdef186d38"
},
"nombre": "iddyo",
"habitantes": "yeto"
}
It´s probably a stupid error but I can´t get my head around it. Thanks a lot!