简体   繁体   中英

Why do model mixins break django-mptt foreign keys?

I'm modifying a third-party Django app based on django-mptt. I'm trying to refactor one monstrously big model into a base class and a set of mixins. All seemed well, however...

class ModelMixin([see below]):
    class Meta:
        abstract = True

class BaseModel(ModelMixin, MPTTModel):
    class Meta:
        abstract = False
  1. If ModelMixin inherits from object , South doesn't see any fields declared in the mixin.
  2. If ModelMixin inherits from mptt.models.MPTTModel , the extra fields that django-mptt adds to MPTT-aware models get added twice; which django-mptt doesn't like, even though the mixin is abstract.
  3. Most interestingly, if ModelMixin inherits from django.db.models.Model , I get this bloody weird error when I try to introduce a foreign key to that model:

Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py"
    line 900, in set_field_name

self.field_name = self.field_name or self.to._meta.pk.name
AttributeError: 'NoneType' object has no attribute 'name'

From the docs :

Please note that if you are using multi-inheritance, MPTTModel should usually be the first class to be inherited from

That doesn't quite explain the behaviour you're seeing, but it probably works around the bug if you also make your mixin derive from models.Model . ie:

class ModelMixin(models.Model):
    class Meta:
        abstract = True

class BaseModel(MPTTModel, ModelMixin):
    class Meta:
        abstract = False

The mixin should definitely derive from models.Model ; the fields won't work if it merely subclasses object because they won't get their contribute_to_class method called by the ModelBase metaclass.

The error you showed in case 3 might be a Django bug; it's hard to tell without a full traceback. Could you add the rest of the traceback context?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM