简体   繁体   English

这个models.Model来自django?

[英]From where this models.Model coming from in django?

As I was creating Django project want to create Models for storing in database later.当我创建 Django 项目时,我想创建模型以便稍后存储在数据库中。 But in the video the person types :但在视频中,人输入:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=20)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User)

Okay, I understand that we are inheriting models class so we can use its properties like CharField, TextField but why we are writing models.Model while inheriting.好的,我知道我们正在继承模型类,所以我们可以使用它的属性,如 CharField、TextField 但为什么我们在继承时编写 models.Model。 Can't we just write models?我们不能只写模型吗? Why he is importing the class method -> Model?为什么他要导入类方法-> 模型? Am I missing something in OOPS?我在 OOPS 中遗漏了什么吗?

Please check the Django's GitHub repository . 请检查Django的GitHub存储库

We can see that models is a package and Model is a class written in its base.py module, hence we could do models.base.Model , but it is made available in __init__.py module, hence we can use it as models.Model . 我们可以看到, 模型是一个包,而模型是在其base.py模块中编写的类,因此我们可以进行models.base.Model ,但可以在__init__.py模块中使用它,因此可以将其用作models.Model

Everything in Python is object so: Python中的所有对象都是对象,因此:

from django.db.models import Model

class Post(Model):
    ...

is the same as this: 与此相同:

from django.db import models

class Post(models.Model):
    ...

So about your question, Can't we just write models? 因此,关于您的问题, Can't we just write models? No, because models is a package which contains a lot of classes and Model is one of these. 不可以,因为模型是一个包含很多类的包,而Model就是其中之一。 So that you have to use models.Model to get the class for class Post to inherit from. 因此,您必须使用models.Model来获取要继承的class Post类的class Post Like I said above, if you want just simply like Model or something, you have to import the right class which you want to use. 就像我在上面说的那样,如果只想像Model之类的东西,就必须导入要使用的正确的类。

Hope that helps! 希望有帮助!

A car os cars.汽车 os 汽车。 A tree of trees Is something like that?一棵树的树是这样的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM