通过我对python的理解,first_name和last_name是类变量,对吧?如何在代码中使用(因为我猜想设置Person.first_name或Person.last_name会影响所有的人的实例)?为什么会这样使用?
解决方案是的,first_name和last_name是类变量。它们定义将在数据库表中创建的字段。有一个Person表有first_name和last_name列,所以在这一点上他们是处于Class级别是有意义的。
有关模型的更多信息,请参阅: docs.djangoproject/en/dev/主题/ db / models /
在代码中访问Person的实例时,您通常通过Django的ORM进行此操作,此时它们基本上表现为实例变量。
有关模型实例的更多信息,请参阅: docs.djangoproject/en/dev/ref/models/instances/?from=olddocs
First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject ) :
class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): # Note use of django.utils.encoding.smart_str() here because # first_name and last_name will be unicode strings. return smart_str('%s %s' % (self.first_name, self.last_name))By my understanding of python , first_name and last_name are class variables , right ? How is that used in code ( because I guess that setting Person.first_name or Person.last_name will affect all Person instances ) ? Why is it used that way ?
解决方案Yes, first_name and last_name are class variables. They define fields that will be created in a database table. There is a Person table that has first_name and last_name columns, so it makes sense for them to be at Class level at this point.
For more on models, see: docs.djangoproject/en/dev/topics/db/models/
When it comes to accessing instances of a Person in code, you are typically doing this via Django's ORM, and at this point they essentially behave as instance variables.
For more on model instances, see: docs.djangoproject/en/dev/ref/models/instances/?from=olddocs
更多推荐
Django模型领域如何工作?
发布评论