MongoEngine / MongoEngine/mongoengine

Problem with copy EmbeddedDocumentListField

Open
#1,962 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

I need copy EmbeddedDocumentListField and I have huge problem because when I use deepcopy I have got error AttributeError: _instance.

Simple example, of error, below:

 from copy import deepcopy
 
 from mongoengine import (
     Document,
     EmbeddedDocument,
     IntField,
     StringField,
     EmbeddedDocumentListField
 )
 
 
 class E(EmbeddedDocument):
     x = IntField(required=True)
     y = IntField(required=True)
 
     def __str__(self):
         return '{}:{}'.format(self.x, self.y)
 
 class A(Document):
     f = StringField(required=True, max_length=256)
     e = EmbeddedDocumentListField(E)
 
 
 a = A(f='a1')
 a.e.append(E(x=1, y=2))
 a.e.append(E(x=10, y=20))
 e_from_a = a.e

 e_copy = deepcopy(e_from_a)

print (type(e_copy) == type(e_from_a))

True

print (e_copy == e_from_a)

True

e_from_a[0]           

<E: 1:2>

But:

e_copy[0]
lib/python3.6/site-packages/mongoengine/base/datastructures.py in __getitem__(self, key, *args, **kwargs)
    116 
    117         EmbeddedDocument = _import_class('EmbeddedDocument')
--> 118         if isinstance(value, EmbeddedDocument) and value._instance is None:
    119             value._instance = self._instance
    120         elif not isinstance(value, BaseDict) and isinstance(value, dict):

AttributeError: _instance

I could copy element by element, but that's not what I mean.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the deepcopy example and inspect mongoengine/base/datastructures.py at the getitem path shown in the traceback. Trace how EmbeddedDocumentListField and its embedded documents are copied; done means a deep-copied list preserves its type and equality and allows indexed access without AttributeError.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.