[英]Receiving "Select a valid choice. That choice is not one of the available choices." while using Djongo ForeignKey with Django
I got this weird error in Django Admin while using the ForeignKey from djongo.models.使用 djongo.models 中的 ForeignKey 时,我在 Django Admin 中遇到了这个奇怪的错误。 Not sure if I did anything wrong in the models file.不确定我是否在模型文件中做错了什么。 Error Message Image错误信息图片
Machine/models.py机器/模型.py
from djongo import models
class Machine(models.Model):
_id = models.ObjectIdField(primary_key=True)
machine_type = models.TextField(null=False)
machine_description = models.TextField(null=False)
def __str__(self):
return self.machine_type
# Create your models here.
class Errorcode(models.Model):
_id = models.ObjectIdField(primary_key=True)
code_name = models.TextField(null=False)
machine_type = models.ForeignKey('Machine', on_delete=models.CASCADE)
description = models.TextField(null=False)
instruction = models.TextField(null=False)
def __str__(self):
return self.code_name
class AdditionalFile(models.Model):
error_code = models.ForeignKey('Errorcode', on_delete=models.CASCADE)
file_name = models.TextField(blank=True)
file_path = models.FileField(blank=True, upload_to='static/asset')
def __str__(self):
return self.file_name
If any other files is needed to inspect the problem, I can add the code here.如果需要任何其他文件来检查问题,我可以在此处添加代码。
Okay so I somehow found a workaround to fix this problem.好的,所以我以某种方式找到了解决此问题的解决方法。 The problem is occurred by the built-in ForeignKey from Django, and djongo doesn't overwrite the ForeignKey to adapt to ObjectID from mongoDB, which make Django confuse using ObjectID as PK.问题出在Django内置的ForeignKey,djongo没有覆盖ForeignKey适配mongoDB的ObjectID,导致Django混淆了使用ObjectID作为PK。
So the workaround is just update the id and use IntegerField as PK所以解决方法是更新 id 并使用 IntegerField 作为 PK
class Machine(models.Model):
id = models.IntegerField(primary_key=True, unique=True)
machine_type = models.TextField(null=False)
machine_description = models.TextField(null=False)
object = models.DjongoManager()
def __str__(self):
return self.machine_type
# Create your models here.
class Errorcode(models.Model):
id = models.IntegerField(primary_key=True, unique=True)
code_name = models.TextField(null=False)
machine_type = models.ForeignKey(to=Machine, to_field='id', on_delete=models.CASCADE)
description = models.TextField(null=False)
instruction = models.TextField(null=False)
object = models.DjongoManager()
def __str__(self):
return self.code_name
.
.
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.