Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
What is the purpose of the class Meta()?
I don't understand why we need a class Meta(). We've used it to define the database in the main class ('db' in this case). Why couldn't we just do that in the main class? How does putting it in this class inside a class help us?
For reference, if you're not looking at the same video at the moment, I'm referring to the following little snippet of code. I know it works, but I don't understand why we bothered with the second class, or why it wouldn't work equally well with the line 'database = db' directly in class Student(Model).
from peewee import * db = SqliteDatabase('students.db') class Student(Model): username = CharField(max_length=255, unique=True) points = IntegerField(default=0) class Meta: database = db
[Edit: formating - cf]
Chris FreemanTreehouse Moderator 68,064 Points
Think of the
Meta class as a container for configuration attributes of the outer class. In
peewee (and also Django), the attributes of a class (for those that inherit from
Model) are expect to be fields that correspond to their counterparts in the database. How then to add attributes that aren't database fields? The
Meta class is the container for these non-field attributes.
As new instances of your outer class are created, the class constructor will look to the
Meta attribute for specific configuration details. More details can be found in the peewee docs and in the Django docs
Thanks, Chris. That makes sense. I didn't realize that all Model attributes were supposed to correspond to fields in the database. Now I understand why this particular attribute is separated from the others, via the Meta class.