Calling certain functions when initializing a new mongoengine document












1















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?










share|improve this question



























    1















    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?










    share|improve this question

























      1












      1








      1








      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?










      share|improve this question














      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?







      python mongoengine






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 23:23









      guyshguysh

      62




      62
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403118%2fcalling-certain-functions-when-initializing-a-new-mongoengine-document%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            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.






            share|improve this answer




























              0














              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.






              share|improve this answer


























                0












                0








                0







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 30 '18 at 7:28









                guyshguysh

                62




                62
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403118%2fcalling-certain-functions-when-initializing-a-new-mongoengine-document%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Tangent Lines Diagram Along Smooth Curve

                    Yusuf al-Mu'taman ibn Hud

                    Zucchini