I have installed MongoDB in my Django project. Because is the first time I use Mongo, I decided to try how it works and I created a simple program to store data ( price and quantity in my case). The project is called "exchange" and it has 2 folders: exchange and app.
This is the file models.py from 'app' folder:
from django.db import models
from djongo.models.fields import ObjectIdField, Field
from django.contrib.auth.models import User
class Profile(models.Model):
_id = ObjectIdField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Order(models.Model):
_id = ObjectIdField()
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
datetime = models.DateTimeField(auto_now_add=True)
price = models.FloatField()
quantity = models.FloatField()
#ips = models.Field(default=[])
#subprofiles = models.Field(default={})
This is the file admin.py
from django.contrib import admin
from .models import *
admin.site.register(Profile)
admin.site.register(Order)
This is how I set the database in the file settings.py of the exchange folder
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'engine',
}
}
So after made the migrations and create the superuser, I run the server, I went into the section Admin than in Profile, and I created a profile choosing the only option available (my superuser). At this point I created an order in the Orders section: so I chose in the "profile" field the only option available (the profile created before), then I filled the other 2 fields (price and quantity), but when I try to save it, appears above the field "profile" the following error:
"Select a valid choice. That choice is not one of the available choices."
I cannot understand where I am wrong.
Thanks in advance for your help!
The issue is that ForeignKey by default appends _id to the property name. In your above example, it is trying to use the property user_id on Profile and profile_id on Order.
The solution is to update the ForeignKey to:
profile = models.ForeignKey(Profile, db_column='profile', on_delete=models.CASCADE)
What you change db_column to may depend on how you have your schema set up inside mongodb, but I was receiving this same error and point the db_column to the correct property fixed it for me.
OMG @Adam Berg , I have been trying to resolve this issue for more than past 4 hours .Your answer resolved it within in mints .Thank you so much , your work is much appreciable.
import datetime,os
from djongo import models
class test1(models.Model):
name = models.CharField(max_length=100)
class Profile(models.Model):
user = models.ForeignKey(test1, db_column='user',on_delete=models.CASCADE)
This Will help you to perform all the foreign key related Query.