skip to Main Content

I have a Django backend project connected to a Mongo database.
I want to manually and personally define the field ID inside this class to be stored in the database so that Django and Mongo can communicate with each other so that I can edit or delete through the Django admin panel.

from djongo import models

class Category2(models.Model):

    # id =
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    price = models.PositiveIntegerField()


    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name
   

Unfortunately, I have no idea how to do it

2

Answers


  1. from djongo import models
    
    class Category2(models.Model):
        _id = models.ObjectIdField(primary_key=True, default=None)
        name = models.CharField(max_length=200)
        slug = models.SlugField(max_length=200, unique=True)
        price = models.PositiveIntegerField()
    
        class Meta:
            ordering = ('name',)
    
        def __str__(self):
            return self.name
    

    NOTE – After making changes to your model, you may need to perform migrations (python manage.py makemigrations and python manage.py migrate)

    Login or Signup to reply.
  2. By default, Django use a hidden primary key field, an integer, that is autoincremented. If you want to use another field type, for example CharField(), you need to add the primary_key=True to that CharField. Example:

    class Category2(models.Model):
        id = models.CharField(max_length=32, primary_key=True)
        # ...
    

    Source: Automatic primary key fields

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search