1

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.

LatoWolf
  • 9
  • 1
  • The error telling your choice not matching with your model choice. You choice probably not matching with your model choice. – boyenec Aug 13 '21 at 09:43
  • @boyenec I think I am choosing the correct model, in this case, django admin is listing all Machine models in my mongoDB to select, however, the Admin is not letting me using the model I selected as ForeignKey – LatoWolf Aug 13 '21 at 09:54

1 Answers1

-1

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
.
.
.
LatoWolf
  • 9
  • 1