Django模型领域如何工作? [英] How do Django model fields work?

查看:111
本文介绍了Django模型领域如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我没有进入网络编程。我碰到了django,看了一些模特儿。我感兴趣的是以下代码(来自djangoproject.com):

  
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆