我有一组已知的JSON数据,从我想要添加到我的Django应用程序的Excel文件中提取。格式如下:
[{" 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"}]
假设我有一个名为Member的模型。如何从此JSON数据创建成员,而不必通过表单手动提交?希望这是有道理的。感谢。
附录:我还必须澄清我在Django应用程序上的对象有一些额外的变量,并丢弃其他变量,所以它不是完全匹配。什么算法可以工作?
更新 (与电子表格数据不同,当前实现是数据的2模型版本。即每个成员都有一个名为Data的相关对象,其中包含大部分变量。记录和日期是实际在Member对象中的唯一变量。其他人是Data对象的一部分)
这是我的模特安排。
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)
答案 0 :(得分:2)
好的,但是我不得不对你的模型做一些改动,所以也许我不明白你想做什么。
带有名称字段的模型我也添加到json中,因此有一些数据要放入,所有字段都可以留空以容纳不完整的数据。
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)
下面的代码将所有json值放入Data实例中,然后在Data的save方法中创建一个新的Member实例。简单地丢弃未使用的值。
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()
结果:
会员
1 Joe
2 Jane
数据
1 1 Initial task completed Just a description
2 2 A different task completed Just another description