这是参考了一个很好的答案我可以使用 JSON 数据在 Django 中添加新对象吗?
但是我对这个组件的工作方式特别感兴趣: member, _ = Member.objects.get_or_create(name = self.name) 请查看上下文和下面的语句。
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):
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 = [{" 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()
请注意,从技术上讲,self.name 正在访问我的数据对象中的 name 变量,实际上我的数据对象模型定义中不存在 name 变量。所以这是我问题的核心:这段代码是如何工作的?这让我觉得有某种临时数据对象在被丢弃之前确实包含 Data.name(又名 self.name),因为它在数据的 JSON 表示中,但不在我的 Data 对象上。