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 trialSahar Nasiri
7,454 PointsMeta Class
I really don't understand why do we need this Meta class? I erased it and nothing has changed! I don't understand the use of this class when we do not make any instances of it.
1 Answer
Igor Yamshchykov
24,397 PointsMeta inner class in Django models: This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name. For instance if you want to specify single or plural names for your model instances you will use Meta class for that. Or default ordering can be also specified there. So you don't need to create instances of this class by yourself, but your Django models will use it.
class Meta:
verbose_name_plural = "products"
Like so.
You can also check out the explanation in Django docs, they have great clarification there https://docs.djangoproject.com/en/dev/topics/db/models/#meta-options
Hope that helps =)
Sahar Nasiri
7,454 PointsSahar Nasiri
7,454 PointsThanks, Igor :)). One question, I remember in Java, a class cannot be used unless you make an instance of that class, is it different here? Python uses inner classes anyway?
Sahar Nasiri
7,454 PointsSahar Nasiri
7,454 PointsSomething else, why does nothing change when I erase this Meta class? Is it because we have only one ordering?
Igor Yamshchykov
24,397 PointsIgor Yamshchykov
24,397 PointsAnswering your question, I'm not sure how this works under the hood in Django, but I bet Django either creates an instance or has some mechanism for accessing properties that you've specify in Meta class. One remark to your note, you can access static methods and properties of the class even if you don't have an class instance I think this applies to Java as well. And yes, referring to the Django documentation Meta to a model is completely optional. So if you need to change some of those properties than you'll need to specify a Meta class, but I you don't change anything there, you can get rid of it.
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsAnother way to view the Meta class used in Django class definitions is as special instructions to the class constructor. These instructions provide ways to customize the inherited
models.Model
clsss.