Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding attributes into Django Model's Meta class

I'm writing a mixin which will allow my Models to be easily translated into a deep dict of values (kind of like .values(), but traversing relationships). The cleanest place to do the definitions of these seems to be in the models themselves, a la:

class Person(models.Model, DeepValues):     name = models.CharField(blank=True, max_length=100)     tribe = models.ForeignKey('Tribes')      class Meta:         schema = {             'name' : str,             'tribe' : {                 'name' : str             }         }  Person.objects.all().deep_values() => {     'name' : 'Andrey Fedorov',     'tribe' : {         'name' : 'Mohicans'     } } 

However, Django complains about my including this in class Meta with:

TypeError: 'class Meta' got invalid attribute(s): schema 

(entire stack trace here)

Now, I suppose I could elaborately override this in my mixin, but is there a more elegant way of storing this information?

like image 557
Andrey Fedorov Avatar asked Jul 06 '09 18:07

Andrey Fedorov


People also ask

What does class Meta do in Django models?

Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.

What is Django Meta class?

Meta 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, whether the model is abstract or not, singular and plural versions of the name etc.

What is App_label in Django?

app_label is used when you have models in a place in which django doesn't know to which app they belong.

What is Verbose_name in Django?

verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface. Syntax – field_name = models.Field(verbose_name = "name")


1 Answers

I don't know about elegant, but one pragmatic way is:

import django.db.models.options as options  options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('schema',) 

Obviously, this would break if Django ever added a 'schema' attribute of its own. But hey, it's a thought...you could always pick an attribute name which is less likely to clash.

like image 180
Vinay Sajip Avatar answered Oct 05 '22 04:10

Vinay Sajip