0

I'm having a document and its sub-document, which works fine without changing anything which exists. When I add new field to the sub-document, while saving I got "you can only reference documents once they have been saved to the database"

class SkillDetail(EmbeddedDocument):
    SkillName = StringField()
    EnrollDate = DateField()
    #newfield = ListField()

class Skills(Document):
    id = IntField()
    Name = StringField()
    SkillsDetails = EmbeddedDocumentField(SkillDetail)

    def update_method(self, skillNamevalue, enrolldate, newFieldValues):
        self.SkillsDetails.append(
            SkillDetail(SkillName=skillNamevalue, EnrollDate=enrolldate, newfield=newFieldValues))
        self.save()

which actually works fine without the newfield in embedded document. But, when I add the newfield (highlighted field in the SkillDetail document) and run the program I got the error mentioned above.

NOTE: actually im calling update_method() method in the Skills class to assign values to the embedded document

kindly help me to solve this problem thanks in advance

bagerard
  • 5,681
  • 3
  • 24
  • 48
Gopi P
  • 525
  • 9
  • 19
  • The code snippet is poor (indentation wrong, typos) and is not complete (e.g: there is no self defined in your example), please provide a reproducible snippet. – bagerard Sep 18 '19 at 06:34
  • @bagerard now I've provided enough information on the question. Please give some advice to proceed further with this. MY work got stopped due to this issue. – Gopi P Sep 19 '19 at 04:36

1 Answers1

0

I had to fix a few things in your code (e.g make id primary key, make SkillsDetails a EmbeddedDocumentListField) but the following works for me:

from mongoengine import *
import datetime as dt

conn = connect()

class SkillDetail(EmbeddedDocument):
   skill_name = StringField()
   enroll_date = DateField()
   newfield = ListField()

class Skills(Document):
   id = IntField(primary_key=True)
   name = StringField()
   skills_details = EmbeddedDocumentListField(SkillDetail)

   def update_method(self, skill_name, enroll_date, new_field_values):
       self.skills_details.append(SkillDetail(skill_name = skill_name, enroll_date=enroll_date, newfield = new_field_values))
       self.save()

sk = Skills(id=1, name='myname')
sk.update_method('a', dt.datetime.utcnow(), [1,2])

existing_sk = Skills.objects.first()
existing_sk.newfield
print(existing_sk.skills_details[0].newfield) # prints "[1, 2]"
bagerard
  • 5,681
  • 3
  • 24
  • 48