为什么 Django 模型使用类变量?
首先,我必须声明我对 Django 还很陌生。
我很乐意创建像这样的类似模型:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
但是,我不明白 django 模型在幕后是如何工作的。我所做的是指定两个类变量,当我说“
person = Person();
person.first_name = 'abc'
我在这段代码中使用的first_name 与我在之前的代码中使用的first_name 相同吗?” 时,我所做的就是指定两个类变量。如果是,first_name应该是models.CharField,但我向它传递了一个字符串,为什么它仍然有效?
First of all, I must declare that I'm quite new to Django.
I'm fine with creating simliar models like this one:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
However, I don't understand how django models works under the cover. What I did was specifying two class variables, when I say
person = Person();
person.first_name = 'abc'
Is the first_name I used in this code the same as the first_name I used in previous code? If yes first_name should be models.CharField, but I'm passing a string to it, how come it still works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不是 django 人,但这看起来很标准......我不确定我是否完全理解你的问题。
正在声明您要输入数据的字段。似乎您正在“模型”数据库中创建一行。
只需填写您创建的 Person 实例的first_name 字段即可。希望这有帮助。
Not a django guy, but this seems pretty standard... I'm not sure if I understood your question completely.
Is declaring the field you are inputting the data into. Seems like youre creating a row in the "models" database.
Is simply filling in the first_name field for the instance of Person you created. Hope this helps.
在第一个示例中,您定义一个类及其类属性。
在第二个示例中,您使用
person = Person()
创建该类的实例(删除不需要的;
)。然后,
model.CharField
的 setter 接受一个字符串,但它仍然是CharField
类型。In the first example, you are defining a class, and its class attributes.
In the second example, you create an instance of that class with
person = Person()
(drop the;
it's not needed).Then, the setter for a
model.CharField
accepts a string, it's still of typeCharField
though.