Can I use JSON data to add new objects in Django?

前端 未结 1 1855
北恋
北恋 2021-01-16 15:47

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,
         


        
相关标签:
1条回答
  • 2021-01-16 16:13

    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   
    
    0 讨论(0)
提交回复
热议问题