BluePython
BluePython

Reputation: 1597

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 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)

Upvotes: 1

Views: 3458

Answers (1)

PhoebeB
PhoebeB

Reputation: 8570

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   

Upvotes: 3

Related Questions