Can I Use Json Data To Add New Objects In Django?
I have a set of known JSON data, extracted from an Excel file that I want to add to my Django application. The format looks like this: [{' Record': 12345, 'Event':' Initial task co
Solution 1:
OK this works, but I have had to make a few changes to your model so maybe I don't understand what you are wanting to do.
Model with a name field that I also added to json so there was some data to put in and all fields can be left blank to accommodate incomplete data.
class Member(models.Model):
name = models.CharField(max_length=30)
record = models.CharField(max_length=200, blank=True, null=True)
pub_date = models.DateTimeField('date', blank=True, null=True)
class Data(models.Model):
member= models.ForeignKey(Member)
dob = models.CharField(max_length=200, blank=True, null=True)
event = models.CharField(max_length=200, blank=True, null=True)
description = models.CharField(max_length=200, blank=True, null=True)
gender = models.CharField(max_length=200, blank=True, null=True)
def save(self, *args, **kwargs):
member, _ = Member.objects.get_or_create(name = self.name)
# can updatemember here with other fields that relate to them
self.member =member
super(Data, self).save(*args, **kwargs)
Code below puts all the json values into an instance of Data then in the save method of Data, a new Member instance is created. Unused values are simply discarded.
json = [{" Record": 12345,
"Name": "Joe",
"Event":" Initial task completed",
"TeamID": 12345,
"IndiviualID":"",
"Description":" Just a description",
"Date": "1/3/13 9:00"},{" Record": 5555,
"Name": "Jane",
"Event":" A different task completed",
"TeamID": 9999,
"IndiviualID":"",
"Description":" Just another description",
"Date": "1/13/13 6:00"}]
foritemin json:
d = Data()
fork,v in item.iteritems():
setattr(d, k.lower(), v)
d.save()
Results in:
Member
1 Joe
2 Jane
Data
11 Initial task completed Just a description
22A different task completed Just another description
Post a Comment for "Can I Use Json Data To Add New Objects In Django?"