[FIXED] Calling certain functions when initializing a new mongoengine document

Issue

I'm trying to define a Document class that has some fields that have their values automatically calculated when a new document is created. So far I have succeeded in doing that by extending the __init__ function like this:

class URLDoc(Document):
    url = fields.URLField(requierd=True)
    domain = fields.StringField(required=True)
    screenshot = fields.ImageField(required=True, size=(600, 600, True), thumbnail=(100, 100, True))

    def __init__(self, *args, **kwargs):
        super(URLDoc, self).__init__(*args, **kwargs)
        self.domain = urlparse(self.url).netloc
        self.get_and_save_screenshot()


    def get_and_save_screenshot(self):
        '''Some code to get a screenshot of the website on self.url'''

        self.screenshot.put(screenshot_file)
        self.save()

This way I was able to create new documents in mongo by just calling new_urldoc = URLDoc(url="some url") and then just new_urldoc.save().

When I started loading existing documents from mongo by URLDoc.objects.get(id="some id") I realized that the __init__ function will be triggered again set new data (take a new screenshot for example) in the document.

I want to implement this but only when the document is new, I looked up everywhere and couldn't find an answer..

Is there a way to call certain functions when initializing a new document as opposed to initializing an existing document?


Solution

I got it working, I don't know if it's a work around or not but I check for self._id (an id is created only on save) on the init function and if there's none (meaning it's a new document), I set the values.



Answered By - guysh
Answer Checked By - Timothy Miller (Python.Easybugfix Admin)

Related Posts

Post a Comment