MongoDB的EmbeddedField中的Django Foreignkey

问题描述

我在Django项目中为MongoDB使用Djongo引擎。

我有两个桌子

# 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')

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

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

    class Meta:
        abstract = True

我想在Answers表中嵌入Questions。 但是我遇到了这个错误

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\'>"']

我知道此错误是因为我在User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE)中使用Answers,而Questions本身是<style> /* do not change */ .container{ overflow: unset; } ul{ margin:0px; padding:0px; list-style-type:none; display:inline-block; } ul li ul li{ display:none; } /* can change */ #container{ text-align:center; } ul li{ background-color:white; border: 1px solid green; width:130px; height:30px; line-height:30px; float:left; text-align:center; margin:5px; border-radius:25px; } ul li a{ color:black; text-decoration:none; display: block; } ul li a:hover{ background-color:red; text-decoration:none; border-radius:25px; color:white; } ul li:hover ul li{ display:block; margin-left:0px; } </style> <div id="container"> <ul> <li><a href='#scroll-section1'>Monkeys</a></li> <li><a href='#scroll-section2'>Option 1</a> <ul> <li><a href='#scroll-section2'>Option a</a></li> <li><a href='https://www.amarketingessentials.com'>Option b</a></li> </ul> </li> <li><a href='#scroll-section3'>Option 2</a></li> <li><a href='#'>Option 3</a></li> <li><a href='#'>Option 4</a></li> </ul> </div>上的EmbeddedField。

如何解决此错误?

由于在同一问题上会有来自不同用户的多个答案,因此使用ForeignKey可以很容易地显示用户的信息及其答案。

我也看过djongo的文档,但找不到任何东西。

任何帮助将不胜感激。

解决方法

IMO 的解决方案是使用昵称作为 Answer 中的字段,并在需要时手动获取 User 对象(按昵称)。我想问题在于 Mongo 中的反向关系实现 - 嵌入的字段没有唯一的 ID,它们只是一些更大文档的一部分(具有 ID 并且可以使用此 ID 访问)。 ForeignKey 中的 EmbeddedField 被禁止,因为无法索引反向关系。

另一种解决方案是将 QuestionAnswer 集合分开,这些集合中的每个文档都有 ID,这样您就可以使用 ex。 ArrayReferenceField (https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/) 来引用它们。在这种情况下,应该允许 ForeignKey 中的 Answer,因为可以使用其 ID 将 Answer 编入索引)。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...