Search code examples
pythondjangomongodbdjongo

mongoDB django _id field instead of id using djongo


trying to learn Django and decided to go with MongoDB and djongo as the connector

now, when I insert a document for mongoDB it is automatically received the _id which is ObjectId from mongodb

I want that when I query all items to get also this _id and I want that when I insert it will not generate the "id" field because I have already the _id, and one more thing when I get one item by id or make a put/delete request I want to check if the id on params is equals to this ObjectId

so this is what I've tried on serialzer.py

from rest_framework import serializers
from .models import Drink
class DrinkSerialzer(serializers.ModelSerializer):
    class Meta:
        model = Drink
        fields = ['_id','name', 'desc']

model.py

from djongo import models


class Drink(models.Model):
    _id = models.ObjectIdField()
    name = models.CharField(max_length=200)
    desc = models.CharField(max_length=500)

and on the requests for example get one by id

from bson import ObjectId

@api_view(['GET', 'PUT', 'DELETE'])
def drink_detail(request, id):

    try:
        drink = Drink.objects.get(_id=ObjectId(id))
    except Drink.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = DrinkSerialzer(drink)
        return Response(serializer.data)

It is not working, with a lot of errors for example

on model: the _id cannot be null

on the request it is said it cannot be the primary key or idk, any suggestions ? thanks for help


Solution

  • Try this:

    from djongo import models
    
    class YourModel(models.Model):
        _id = models.ObjectIdField(primary_key=True, editable=False)
        # Other fields in your model
    
        class Meta:
            db_table = 'your_collection_name'