Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django add_to_class() making models inheritance/MRO work wrong

I have a problem with inheritance on my models when adding fields via add_to_class(). I have a models File(models.Model) and Image(File) - these come from django-filer.

In my app I'm importing them and adding fields and methods:

def method_x(self):
    print "x"

File.add_to_class("expiration_date", models.DateField(null=True, blank=True))
File.add_to_class("method_x", method_x)

Image should inherit both of those but it gets only the method(s), not field(s):

>>> some_file = File.objects.get(id=8)
>>> some_image = Image.objects.get(id=8)
>>>
>>> print some_file.expiration_date # this works
... None
>>>
>>> some_image.metgod_x() # this works
>>> x
>>>
>>> print some_image.expiration_date # and this not
Traceback (most recent call last):
    File "<console>", line 1, in <module>
AttributeError: 'Image' object has no attribute 'expiration_date'

Any clue?

like image 933
grucha Avatar asked Oct 09 '11 13:10

grucha


People also ask

What are the model inheritance style in Django?

Multi-table inheritance: This inheritance style is used if you want to subclass on an existing model and each of the models to have its own database table. Proxy models: This inheritance style allows the user to modify the python level behavior without actually modifying the model's field.

How can create primary key in Django model?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

WHAT IS models ForeignKey?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db.

What is proxy model in Django?

Proxy models allow us to change the Python behavior of a model without changing the database. vehicles/models.py. from django.db import models. class Car(models.Model): vin = models.CharField(max_length=17)


1 Answers

Your model's add_to_class does not add the field as an attribute. it just calls contribute_to_class on your field: django/db/models/base.py#L218

Your field's contribute_to_class does not do it either. It just adds the field to the model's _meta member: django/db/models/fields/__init__.py#L234

like image 190
akonsu Avatar answered Oct 04 '22 16:10

akonsu