setattr()方法是否创建临时对象?

时间:2013-09-12 19:16:10

标签: python django django-models

这是一个很好的答案Can I use JSON data to add new objects in Django?

但是我对此组件的工作方式特别感兴趣:成员,_ = 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在技术上是访问我的Data Object中的name变量,实际上我的Data Object模型定义中不存在name变量。所以这是我的问题的核心:这段代码是如何工作的?它让我觉得有某种临时数据对象在丢弃之前确实包含Data.name(又名self.name),因为它在数据的JSON表示中但不在我的Data对象上。

1 个答案:

答案 0 :(得分:4)

不,这根本不是它的工作方式。

Python对象是动态的。您可以随时定义您喜欢的任何属性。无论您执行setattr(d, "name", "foo")还是d.name = foo都无关紧要,结果完全相同:d实例获得属性name,无论它是否有一个属性{{1}} ,以及班级中是否有提及它的定义。

Django模型添加了自己的特殊语法来定义它们存储在数据库中的字段,但在它下面它们只是Python对象,因此您可以根据需要在它们上动态定义额外的属性。