1

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 completed",
"TeamID": 12345,
"IndiviualID":null,
"Description":" Just a description",
"Date": "1/3/13 9:00"},{" Record": 5555,
"Event":" A different task completed",
"TeamID": 9999,
"IndiviualID":null,
"Description":" Just another description",
"Date": "1/13/13 6:00"}]

Lets say that I have a model called Member. How can I create members from this JSON data instead of having to submit it manually through my forms? Hopefully this makes sense. Thanks.

Addendum: I must also clarify that my object on the Django app has some additional variables, and discards other variables, so it is not an exact match. What algorithm would work?

UPDATE: (Different from the spreadsheet data the current implementation is a 2 model version of the data. Namely every Member has a related object called Data that carries most of the variables. Record and date are the only variables that are actually within the Member object. All others are part of the Data object)

This is my model arrangement.

class Member(models.Model):
    def __unicode__(self):
        return self.record

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Entered recently?'

    record = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date')


class Data(models.Model):
    def __unicode__(self):
        return self.dob

    member = models.ForeignKey(Member)  
    dob = models.CharField(max_length=200)
    event = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    gender = models.CharField(max_length=200)
okm
  • 23,575
  • 5
  • 83
  • 90
BluePython
  • 1,635
  • 3
  • 24
  • 35
  • yes you can, by using django method serializer deserializer, read the topic about that. – drabo2005 Sep 10 '13 at 17:02
  • @drabo2005 correct me if I am wrong, but django serializer requires specific json schema which is completely differenet from example input. Of course it can be converted to correct format, and most of the time it doesn’t too much work, but still it require some job. – zero323 Sep 10 '13 at 17:19
  • @Prussian Can you provide code for your Member class? – zero323 Sep 10 '13 at 17:20

1 Answers1

3

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 update member 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"}]

    for item in json:

        d = Data()

        for k,v in item.iteritems():
            setattr(d, k.lower(), v)

        d.save()

Results in:

Member

1   Joe     
2   Jane        

Data

1   1        Initial task completed  Just a description 
2   2        A different task completed  Just another description   
PhoebeB
  • 8,434
  • 8
  • 57
  • 76
  • thanks so much for such a great answer. I am currently implementing it. Quick question: What does the member, _ means in the def save method. Specifically what is the _ doing? Thanks! – BluePython Sep 12 '13 at 06:13
  • Also can you point out what is super(Data, self).save(*args, **kwargs) doing? Thanks, and sorry for the trouble. – BluePython Sep 12 '13 at 06:18
  • get_or_create return the item and a flag which is true if the item was created. By putting _ I'm saying I don't need that variable. Could just as well have put member, created = .... – PhoebeB Sep 13 '13 at 10:11
  • super calls the parent version of save() which you will always want to do if you are adding to an existing method rather than replacing it. – PhoebeB Sep 13 '13 at 10:12