Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何处理双重引用和随后的导入错误_Python_Python 3.x_Mongodb_Design Patterns_Mongoengine - Fatal编程技术网

Python 如何处理双重引用和随后的导入错误

Python 如何处理双重引用和随后的导入错误,python,python-3.x,mongodb,design-patterns,mongoengine,Python,Python 3.x,Mongodb,Design Patterns,Mongoengine,我在导入和引用方面遇到了问题。我将用一个虚构的例子来解释(这个例子使用了mongoengine) 假设我在两个不同的文件中有以下两个类 # File 1 # Titled houses.py import persons import mongoengine as me class House(me.Document): residents: me.ListField(me.ReferenceField(persons.Person)) #This will be a list p

我在导入和引用方面遇到了问题。我将用一个虚构的例子来解释(这个例子使用了mongoengine)

假设我在两个不同的文件中有以下两个类

# File 1 
# Titled houses.py

import persons
import mongoengine as me

class House(me.Document):
    residents: me.ListField(me.ReferenceField(persons.Person)) #This will be a list populated with Person objects
在上述场景中,我有两个顾虑

  • 我得到一个循环导入错误(b/c他们相互需要)-我无法摆脱导入b/c mongo要求您输入将分配给变量的对象的类
  • 这似乎不太理想-有没有更好的设计模式

  • 谢谢

    您似乎可以将
    字符串
    参数传递到
    引用字段
    ,它应该可以解决您的问题

    文件1:

    import mongoengine as me
    
    class House(me.Document):
        residents: me.ListField(me.ReferenceField("Person"))
    
    文件2:

    import mongoengine as me
    
    class Person(me.Document):
        house: me.ReferenceField("House")
    
    import mongoengine as me
    
    class Person(me.Document):
        house: me.ReferenceField("House")