Django模型和放大器; Python类属性 [英] Django models & Python class attributes

查看:194
本文介绍了Django模型和放大器; Python类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django的网站上的教程演示了这个code代表机型:

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()

现在,每一个这些属性,是一个类属性,对不对?所以,相同的属性应该由类的所有实例共享。过了一会儿,他们present这个code:

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 类。通过一些有阶级属性转向实例属性如

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)

有人可能会建议将整个文件(模型库模式类)作为一个优秀的动手例如在元类

One might recommend the whole file (ModelBase and Model class) as an excellent hands-on example on metaclasses.

这篇关于Django模型和放大器; Python类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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