简体   繁体   中英

From where this models.Model coming from in django?

As I was creating Django project want to create Models for storing in database later. 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. Can't we just write models? Why he is importing the class method -> Model? Am I missing something in OOPS?

Please check the Django's GitHub repository .

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 .

Everything in Python is object so:

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? No, because models is a package which contains a lot of classes and Model is one of these. So that you have to use models.Model to get the class for class Post to inherit from. 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.

Hope that helps!

A car os cars. A tree of trees Is something like that?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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