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 trialDaniel Rosensweig
5,074 PointsWhat 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]
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsThink 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
Daniel Rosensweig
5,074 PointsThanks, 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.