Django models amp; Python class attributes(Django 模型与Python 类属性)
问题描述
django 网站上的教程显示了模型的以下代码:
The tutorial on the django website shows this code for the models:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
现在,这些属性中的每一个都是类属性,对吧?因此,该类的所有实例都应共享相同的属性.稍后,他们展示了这段代码:
Now, each of those attribute, is a class attribute, right? So, the same attribute should be shared by all instances of the class. A bit later, they present this code:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
它们是如何从类属性转变为实例属性的?我是不是把类属性弄错了?
How did they turn from class attributes into instance attributes? Did I get class attributes wrong?
推荐答案
看看django/db/models.py下的Model
类.在那里,类属性通过类似的方式转换为实例属性
Have a look at the Model
class under django/db/models.py. There the class attributes are turned to instance attributes via something like
setattr(self, field.attname, val)
人们可能会推荐整个文件(ModelBase
和 Model
类)作为元类的优秀实践示例.
One might recommend the whole file (ModelBase
and Model
class) as an excellent hands-on example on metaclasses.
这篇关于Django 模型与Python 类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django 模型与Python 类属性


基础教程推荐
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01