How to Add a method to the model that takes JSON string and creates new records












0














I need to Create two Django models: “Patient” and “Embryo”.



“Patient” properties:
First Name (string)
Last Name (string)
Telephone Number (string)
Email (string)
Created At (datetime)



“Embryo” properties:
Name (string)
Analysis Results (text)
Created At (datetime)
Patient’s Full Name
Patient (foreign key)



I now need to Add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.
Here’s the JSON string:



[
{
"name": "embryo_1",
"analysis_results": "46,XX"
},
{
"name": "embryo_2",
"analysis_results": "47,XY,+21"
},
{
"name": "embryo_3",
"analysis_results": "46,XY"
},
]


Below are my models that I created
I am not sure how to add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.



class Patient(models.Model):
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=35)
phone = models.CharField(max_length=18)
email = models.EmailField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)



class Embryo(models.Model):
name = models.CharField(max_length=45)
analysis_result = models.Charfield(max_length=10)
created_at = models.DateTimeField(auto_now_add=True)
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)

@property
def patient_full_name(self):
return "%s %s" % (self.patient.first_name, self.patient.last_name)









share|improve this question



























    0














    I need to Create two Django models: “Patient” and “Embryo”.



    “Patient” properties:
    First Name (string)
    Last Name (string)
    Telephone Number (string)
    Email (string)
    Created At (datetime)



    “Embryo” properties:
    Name (string)
    Analysis Results (text)
    Created At (datetime)
    Patient’s Full Name
    Patient (foreign key)



    I now need to Add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.
    Here’s the JSON string:



    [
    {
    "name": "embryo_1",
    "analysis_results": "46,XX"
    },
    {
    "name": "embryo_2",
    "analysis_results": "47,XY,+21"
    },
    {
    "name": "embryo_3",
    "analysis_results": "46,XY"
    },
    ]


    Below are my models that I created
    I am not sure how to add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.



    class Patient(models.Model):
    first_name = models.CharField(max_length=25)
    last_name = models.CharField(max_length=35)
    phone = models.CharField(max_length=18)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)



    class Embryo(models.Model):
    name = models.CharField(max_length=45)
    analysis_result = models.Charfield(max_length=10)
    created_at = models.DateTimeField(auto_now_add=True)
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)

    @property
    def patient_full_name(self):
    return "%s %s" % (self.patient.first_name, self.patient.last_name)









    share|improve this question

























      0












      0








      0







      I need to Create two Django models: “Patient” and “Embryo”.



      “Patient” properties:
      First Name (string)
      Last Name (string)
      Telephone Number (string)
      Email (string)
      Created At (datetime)



      “Embryo” properties:
      Name (string)
      Analysis Results (text)
      Created At (datetime)
      Patient’s Full Name
      Patient (foreign key)



      I now need to Add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.
      Here’s the JSON string:



      [
      {
      "name": "embryo_1",
      "analysis_results": "46,XX"
      },
      {
      "name": "embryo_2",
      "analysis_results": "47,XY,+21"
      },
      {
      "name": "embryo_3",
      "analysis_results": "46,XY"
      },
      ]


      Below are my models that I created
      I am not sure how to add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.



      class Patient(models.Model):
      first_name = models.CharField(max_length=25)
      last_name = models.CharField(max_length=35)
      phone = models.CharField(max_length=18)
      email = models.EmailField(unique=True)
      created_at = models.DateTimeField(auto_now_add=True)



      class Embryo(models.Model):
      name = models.CharField(max_length=45)
      analysis_result = models.Charfield(max_length=10)
      created_at = models.DateTimeField(auto_now_add=True)
      patient = models.ForeignKey(Patient, on_delete=models.CASCADE)

      @property
      def patient_full_name(self):
      return "%s %s" % (self.patient.first_name, self.patient.last_name)









      share|improve this question













      I need to Create two Django models: “Patient” and “Embryo”.



      “Patient” properties:
      First Name (string)
      Last Name (string)
      Telephone Number (string)
      Email (string)
      Created At (datetime)



      “Embryo” properties:
      Name (string)
      Analysis Results (text)
      Created At (datetime)
      Patient’s Full Name
      Patient (foreign key)



      I now need to Add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.
      Here’s the JSON string:



      [
      {
      "name": "embryo_1",
      "analysis_results": "46,XX"
      },
      {
      "name": "embryo_2",
      "analysis_results": "47,XY,+21"
      },
      {
      "name": "embryo_3",
      "analysis_results": "46,XY"
      },
      ]


      Below are my models that I created
      I am not sure how to add a method to the “Patient” model that takes JSON string and creates new “Embryo” records.



      class Patient(models.Model):
      first_name = models.CharField(max_length=25)
      last_name = models.CharField(max_length=35)
      phone = models.CharField(max_length=18)
      email = models.EmailField(unique=True)
      created_at = models.DateTimeField(auto_now_add=True)



      class Embryo(models.Model):
      name = models.CharField(max_length=45)
      analysis_result = models.Charfield(max_length=10)
      created_at = models.DateTimeField(auto_now_add=True)
      patient = models.ForeignKey(Patient, on_delete=models.CASCADE)

      @property
      def patient_full_name(self):
      return "%s %s" % (self.patient.first_name, self.patient.last_name)






      django python-3.x django-models django-rest-framework






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 1:38









      SamirTendulkar

      18111




      18111
























          2 Answers
          2






          active

          oldest

          votes


















          1














          You can add an instance method to the model class, just like any other python class.




          • Load the dict from json string, (preferably, using json.loads).

          • Instantiate a list of Embryo objects.

          • Pass the list to bulk_create method to create multiple objects in one query.


          Example:



          import json

          class Patient(models.Model):
          # fields

          def add_embryos(self, embryos_json_str='{}'):
          embryos = json.loads(embryos_json_str)

          embryo_objs =
          for embryo in embryos:
          embryo_objs.append(Embryo(
          name=embryo['name'],
          analysis_result=embryo['analysis_results'],
          patient=self
          ))

          Embryo.objects.bulk_create(embryo_objs)


          NOTE:




          • You can wrap json.loads in a try-except block to not raise any unnecessary exceptions.

          • If too many embryos objects in json, use batch_size argument of bulk_create to insert in batches.






          share|improve this answer























          • How do I import json to add to the above code embryos = json.loads(embryos_json_str)
            – SamirTendulkar
            Nov 13 at 13:17










          • Oh. Missed that. Updating answer. Thanks!
            – Sachin Kukreja
            Nov 14 at 4:59



















          0














          A method specifically to do this may not be necessary:



          You can use python's json.loads() to load into a list of dictionaries, and then loop over to create the models.



          import json


          At the beginning of your file, then in your view:



          #get the string from your request or form or wherever you get it
          dict_list = json.loads('[{...}, {...}, {...}]'

          for entry in dict_list:
          Embryo.objects.create(**entry)


          the (**entry) syntax unpacks your dict into kwargs



          Hope this solves your problem! :)






          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%2f53254993%2fhow-to-add-a-method-to-the-model-that-takes-json-string-and-creates-new-records%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can add an instance method to the model class, just like any other python class.




            • Load the dict from json string, (preferably, using json.loads).

            • Instantiate a list of Embryo objects.

            • Pass the list to bulk_create method to create multiple objects in one query.


            Example:



            import json

            class Patient(models.Model):
            # fields

            def add_embryos(self, embryos_json_str='{}'):
            embryos = json.loads(embryos_json_str)

            embryo_objs =
            for embryo in embryos:
            embryo_objs.append(Embryo(
            name=embryo['name'],
            analysis_result=embryo['analysis_results'],
            patient=self
            ))

            Embryo.objects.bulk_create(embryo_objs)


            NOTE:




            • You can wrap json.loads in a try-except block to not raise any unnecessary exceptions.

            • If too many embryos objects in json, use batch_size argument of bulk_create to insert in batches.






            share|improve this answer























            • How do I import json to add to the above code embryos = json.loads(embryos_json_str)
              – SamirTendulkar
              Nov 13 at 13:17










            • Oh. Missed that. Updating answer. Thanks!
              – Sachin Kukreja
              Nov 14 at 4:59
















            1














            You can add an instance method to the model class, just like any other python class.




            • Load the dict from json string, (preferably, using json.loads).

            • Instantiate a list of Embryo objects.

            • Pass the list to bulk_create method to create multiple objects in one query.


            Example:



            import json

            class Patient(models.Model):
            # fields

            def add_embryos(self, embryos_json_str='{}'):
            embryos = json.loads(embryos_json_str)

            embryo_objs =
            for embryo in embryos:
            embryo_objs.append(Embryo(
            name=embryo['name'],
            analysis_result=embryo['analysis_results'],
            patient=self
            ))

            Embryo.objects.bulk_create(embryo_objs)


            NOTE:




            • You can wrap json.loads in a try-except block to not raise any unnecessary exceptions.

            • If too many embryos objects in json, use batch_size argument of bulk_create to insert in batches.






            share|improve this answer























            • How do I import json to add to the above code embryos = json.loads(embryos_json_str)
              – SamirTendulkar
              Nov 13 at 13:17










            • Oh. Missed that. Updating answer. Thanks!
              – Sachin Kukreja
              Nov 14 at 4:59














            1












            1








            1






            You can add an instance method to the model class, just like any other python class.




            • Load the dict from json string, (preferably, using json.loads).

            • Instantiate a list of Embryo objects.

            • Pass the list to bulk_create method to create multiple objects in one query.


            Example:



            import json

            class Patient(models.Model):
            # fields

            def add_embryos(self, embryos_json_str='{}'):
            embryos = json.loads(embryos_json_str)

            embryo_objs =
            for embryo in embryos:
            embryo_objs.append(Embryo(
            name=embryo['name'],
            analysis_result=embryo['analysis_results'],
            patient=self
            ))

            Embryo.objects.bulk_create(embryo_objs)


            NOTE:




            • You can wrap json.loads in a try-except block to not raise any unnecessary exceptions.

            • If too many embryos objects in json, use batch_size argument of bulk_create to insert in batches.






            share|improve this answer














            You can add an instance method to the model class, just like any other python class.




            • Load the dict from json string, (preferably, using json.loads).

            • Instantiate a list of Embryo objects.

            • Pass the list to bulk_create method to create multiple objects in one query.


            Example:



            import json

            class Patient(models.Model):
            # fields

            def add_embryos(self, embryos_json_str='{}'):
            embryos = json.loads(embryos_json_str)

            embryo_objs =
            for embryo in embryos:
            embryo_objs.append(Embryo(
            name=embryo['name'],
            analysis_result=embryo['analysis_results'],
            patient=self
            ))

            Embryo.objects.bulk_create(embryo_objs)


            NOTE:




            • You can wrap json.loads in a try-except block to not raise any unnecessary exceptions.

            • If too many embryos objects in json, use batch_size argument of bulk_create to insert in batches.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 14 at 5:00

























            answered Nov 12 at 2:51









            Sachin Kukreja

            2,0351716




            2,0351716












            • How do I import json to add to the above code embryos = json.loads(embryos_json_str)
              – SamirTendulkar
              Nov 13 at 13:17










            • Oh. Missed that. Updating answer. Thanks!
              – Sachin Kukreja
              Nov 14 at 4:59


















            • How do I import json to add to the above code embryos = json.loads(embryos_json_str)
              – SamirTendulkar
              Nov 13 at 13:17










            • Oh. Missed that. Updating answer. Thanks!
              – Sachin Kukreja
              Nov 14 at 4:59
















            How do I import json to add to the above code embryos = json.loads(embryos_json_str)
            – SamirTendulkar
            Nov 13 at 13:17




            How do I import json to add to the above code embryos = json.loads(embryos_json_str)
            – SamirTendulkar
            Nov 13 at 13:17












            Oh. Missed that. Updating answer. Thanks!
            – Sachin Kukreja
            Nov 14 at 4:59




            Oh. Missed that. Updating answer. Thanks!
            – Sachin Kukreja
            Nov 14 at 4:59













            0














            A method specifically to do this may not be necessary:



            You can use python's json.loads() to load into a list of dictionaries, and then loop over to create the models.



            import json


            At the beginning of your file, then in your view:



            #get the string from your request or form or wherever you get it
            dict_list = json.loads('[{...}, {...}, {...}]'

            for entry in dict_list:
            Embryo.objects.create(**entry)


            the (**entry) syntax unpacks your dict into kwargs



            Hope this solves your problem! :)






            share|improve this answer




























              0














              A method specifically to do this may not be necessary:



              You can use python's json.loads() to load into a list of dictionaries, and then loop over to create the models.



              import json


              At the beginning of your file, then in your view:



              #get the string from your request or form or wherever you get it
              dict_list = json.loads('[{...}, {...}, {...}]'

              for entry in dict_list:
              Embryo.objects.create(**entry)


              the (**entry) syntax unpacks your dict into kwargs



              Hope this solves your problem! :)






              share|improve this answer


























                0












                0








                0






                A method specifically to do this may not be necessary:



                You can use python's json.loads() to load into a list of dictionaries, and then loop over to create the models.



                import json


                At the beginning of your file, then in your view:



                #get the string from your request or form or wherever you get it
                dict_list = json.loads('[{...}, {...}, {...}]'

                for entry in dict_list:
                Embryo.objects.create(**entry)


                the (**entry) syntax unpacks your dict into kwargs



                Hope this solves your problem! :)






                share|improve this answer














                A method specifically to do this may not be necessary:



                You can use python's json.loads() to load into a list of dictionaries, and then loop over to create the models.



                import json


                At the beginning of your file, then in your view:



                #get the string from your request or form or wherever you get it
                dict_list = json.loads('[{...}, {...}, {...}]'

                for entry in dict_list:
                Embryo.objects.create(**entry)


                the (**entry) syntax unpacks your dict into kwargs



                Hope this solves your problem! :)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 12 at 2:43

























                answered Nov 12 at 2:37









                robotHamster

                343115




                343115






























                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2f53254993%2fhow-to-add-a-method-to-the-model-that-takes-json-string-and-creates-new-records%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







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Error while running script in elastic search , gateway timeout

                    Adding quotations to stringified JSON object values