I'm using djongo package for a database backend engine in order to connect to MongoDB and define my models on it.
settings.py:
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': str(BASE_DIR / 'db.sqlite3'),
# },
'default': {
'ENGINE': 'djongo',
'NAME': 'djongo-db',
'ENFORCE_SCHEMA': False,
'CLIENT': {
'host': 'localhost',
'port': 27017,
'username': 'root',
'password': 'root',
'authSource': 'admin',
'authMechanism': 'SCRAM-SHA-1'
}
}
}
models.py:
class EventModel(BaseModel)
name = models.CharField(max_length=20)
class CalendarModel(BaseModel):
name = models.CharField(max_length=20)
color = models.CharField(max_length=20)
event = models.ForeignKey(to=EventModel, on_delete=models.SET_NULL, null=True)
and admin.py:
from django.contrib import admin
from .models import CalendarModel, EventModel
@admin.register(CalendarModel)
class CalendarAdmin(admin.ModelAdmin):
exclude = ['_id']
@admin.register(EventModel)
class EventAdmin(admin.ModelAdmin):
exclude = ['_id']
It works fine with using SQLite backend and it's working when djongo backend without foreign key field but gives me an error when using the djongo backend and has foreign key field. It said:
As you can see in the image above, it can load objects from the database and detects the relation correctly, but it can't save it.
And I can't create a new object with relation to another object. How I can fix this?
Update
I can create objects using code like this, the problem seems to be from Django admin site
e = EventModel.objects.first()
CalendarModel.objects.create(name="test", color="red", event=e)