Hi.
I’m new in Django.
I decided to learn Django from the Django website. But I can’t understand one thing.
In the tutorial, it makes models like this:
(models.py)
My code is run by this tutorial but I want to understand it correctly.
In Question class, we have no function like objects. what is objects? Where does it from?
Thank you.
How much of Python do you know? That will determine your learning speed. Do you know a bit about Python Classes, … I mean an ordinary Class? If not, start there.
In your question you defined a class called “Question”. That is what the first line does. class Question(models.Model):
But you didn’t just define the class normally, you made the class a subclass of an existing one (models.Model). So your “Question” class took some methods and attributes from “models.Model”. The objects were described in “models.Model” (I hope i am right since I haven’t looked at the definition of “models.Model” before. You got “objects” from “models.Model” all the same
Actually… That description may be ok from a “mental model” / “conceptual” perspective, but it’s technically not correct.
Model classes are not built by inheriting from the base class. They’re constructed dynamically from the ModelBase metaclass. It’s this dynamic construction that allows for you to rename the objects manager to something else - allowing you to re-use that name for other purposes.
There’s a lot more going on there than meets the eye, and recognizing and understanding that helps a great deal when you want to modify a model’s behavior. (For example, that’s one of the reasons why you never want to override the model’s __init__ method - that rarely does what you think or expect it would do.)