4

I am using Djongo engine for MongoDB in my Django project.

I have two tables

# app/models.py
# My Main Table

class Questions(models.Model):
    questionId = models.UUIDField(default=uuid.uuid4, editable=True, unique=True)
    question = models.TextField()
    answer = models.EmbeddedField(
        model_container=Answers
    )
    date = models.DateTimeField(auto_now_add=True, blank=True)
    User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE,related_name='userinfo')

and

# app/models.py
# This table needs to be Embedded in Questions Table

class Answers(models.Model):
    answerId = models.UUIDField(default=uuid.uuid4, editable=True, unique=True)
    answer = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE)

    class Meta:
        abstract = True

I want to embed Answers in the Questions table. But I am getting this error

django.core.exceptions.ValidationError: ['Field "App.Answers.User" of model container:"<class \'App.models.Answers\'>" cannot be of type "<class \'django.db.models.fields.related.ForeignKey\'>"']

I know this error is because I am using User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE) in Answers which is itself an EmbeddedField on Questions.

How Can I solve this error?

As there will be multiple answers from different users on the same question and with ForeignKey it will be simple to show the user's info along with his/her answer.

I have also looked djongo's docs but couldn't find anything.

Any help would be appreciated.

danish2694
  • 199
  • 3
  • 16

1 Answers1

1

IMO the solution is to use nickname as a field in Answer and manually fetch User object (by nickname) when needed. I suppose that the problem lays in reverse relation implementation in Mongo - embedded fields don't have unique IDs, they're only part of some bigger document (that has ID and can be reached using this ID). ForeignKey in EmbeddedField is forbidden because reverse relation can't be indexed.

The other solution is to separate Question and Answer collections that each document in these collections does have ID so then you can use ex. ArrayReferenceField (https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/) to reference them. In this case ForeignKey in Answer should be allowed because of the ability to index Answer with its ID).

Konrad Sikorski
  • 399
  • 5
  • 11