Django模型领域如何工作?

编程入门 行业动态 更新时间:2024-10-25 01:35:47
本文介绍了Django模型领域如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 首先,我没有进入网络编程。我碰到了django,看了一些模特儿。我感兴趣的是以下代码(来自djangoproject):

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级别是有意义的。

有关模型的更多信息,请参阅: 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模型领域如何工作?

本文发布于:2023-11-25 13:48:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   领域   工作   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!