Django模型领域如何工作? [英] How do Django model fields work?
问题描述
class Person(models.Model)
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
def __str __(self):
#注意使用django.utils.encoding.smart_str()这里因为
#first_name和last_name将是unicode字符串。
返回smart_str('%s%s'%(self.first_name,self.last_name))
通过我对python的理解,first_name和last_name是类变量,对吧?如何在代码中使用(因为我猜想设置Person.first_name或Person.last_name会影响所有的人的实例)?为什么会这样使用?
是的,first_name和last_name是类变量。它们定义将在数据库表中创建的字段。有一个Person表有first_name和last_name列,所以在这一点上他们是处于Class级别是有意义的。
有关模型的更多信息,请参阅:
http://docs.djangoproject.com/en/dev/主题/ db / models /
在代码中访问Person的实例时,您通常通过Django的ORM进行此操作,此时它们基本上表现为实例变量。
有关模型实例的更多信息,请参阅:
http://docs.djangoproject.com/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.com ) :
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: http://docs.djangoproject.com/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: http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs
这篇关于Django模型领域如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!