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?
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.
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).
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With