Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Basics Model Administration Adding Instances

Sahar Nasiri
Sahar Nasiri
7,454 Points

There is no constructor

We have not write any init function for our Course class, how come we can pass values to our attributes while we are building an instance of the Course class?

>>> Course(title="Python Collections", description="Learn about list, dict and tuple").save()  

2 Answers

Kristian Gausel
Kristian Gausel
14,661 Points

Because in django it is probably written using **keywordargs. So it just takes the keywords you specify and add them.

you can write your own constructor like this in a way close to this:

class Example(object):
    def __init__(self, *args, **kwargs):
        self.data = kwargs

Remember that we are inheriting from the models.Model class. So those functions should be there.

According to "yak" on Stack Overflow: "In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes init. So if you don't define it in your class, you will get the one from the base...."

See: https://stackoverflow.com/questions/10482953/python-extending-with-using-super-python-3-vs-python-2

Also see the docs for models.Model Notice it takes in **kwargs. see: https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model

Hope this helps