How to Add a method to the model that takes JSON string and creates new records
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
add a comment |
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
add a comment |
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
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
django python-3.x django-models django-rest-framework
asked Nov 12 at 1:38
SamirTendulkar
18111
18111
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
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 atry-except
block to not raise any unnecessary exceptions. - If too many embryos objects in json, use
batch_size
argument ofbulk_create
to insert in batches.
How do I importjson
to add to the above codeembryos = json.loads(embryos_json_str)
– SamirTendulkar
Nov 13 at 13:17
Oh. Missed that. Updating answer. Thanks!
– Sachin Kukreja
Nov 14 at 4:59
add a comment |
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! :)
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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 atry-except
block to not raise any unnecessary exceptions. - If too many embryos objects in json, use
batch_size
argument ofbulk_create
to insert in batches.
How do I importjson
to add to the above codeembryos = json.loads(embryos_json_str)
– SamirTendulkar
Nov 13 at 13:17
Oh. Missed that. Updating answer. Thanks!
– Sachin Kukreja
Nov 14 at 4:59
add a comment |
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 atry-except
block to not raise any unnecessary exceptions. - If too many embryos objects in json, use
batch_size
argument ofbulk_create
to insert in batches.
How do I importjson
to add to the above codeembryos = json.loads(embryos_json_str)
– SamirTendulkar
Nov 13 at 13:17
Oh. Missed that. Updating answer. Thanks!
– Sachin Kukreja
Nov 14 at 4:59
add a comment |
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 atry-except
block to not raise any unnecessary exceptions. - If too many embryos objects in json, use
batch_size
argument ofbulk_create
to insert in batches.
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 atry-except
block to not raise any unnecessary exceptions. - If too many embryos objects in json, use
batch_size
argument ofbulk_create
to insert in batches.
edited Nov 14 at 5:00
answered Nov 12 at 2:51
Sachin Kukreja
2,0351716
2,0351716
How do I importjson
to add to the above codeembryos = json.loads(embryos_json_str)
– SamirTendulkar
Nov 13 at 13:17
Oh. Missed that. Updating answer. Thanks!
– Sachin Kukreja
Nov 14 at 4:59
add a comment |
How do I importjson
to add to the above codeembryos = 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
add a comment |
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! :)
add a comment |
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! :)
add a comment |
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! :)
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! :)
edited Nov 12 at 2:43
answered Nov 12 at 2:37
robotHamster
343115
343115
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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