简体   繁体   中英

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. Not sure if I did anything wrong in the models file. Error Message Image

Machine/models.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.

So the workaround is just update the id and use IntegerField as 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
.
.
.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM