1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# models.py from model_utils.managers import InheritanceManager class AbstractProduct(models.Model): objects = InheritanceManager() class ProductA(AbstractProduct): pass class ProductB(AbstractProduct): pass # shell AbstractProduct.objects.filter(id=1).select_subclasses() |
Abstract classes such as AbstractProduct which inherit from third party package model_utils.InheritanceManage, will not work with abstract attribute specified true:
1 2 |
class Meta: abstract = True |
For this reason, its subclass like ProductA will cause create issue when load fixtures data by running this command:
1 |
$ python manage.py loaddata <file-name> |
Which will not raise errors also not writing into database, see the same issue on stackoverflow
The solution here is provide post_save signal and execute save(), because loaddata command will not call pre_save() and save()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from django.db.models.signals import post_save class ProductA(AbstractProduct): pass def instance_post_save(sender, instance, created, **kwargs): if kwargs.get('raw'): instance.save() return post_save.connect(instance_post_save, sender=ProductA)from django.db.models.signals import post_save |
1 2 3 4 5 6 7 8 9 10 |
class ProductA(AbstractProduct): pass def instance_post_save(sender, instance, created, **kwargs): if kwargs.get('raw'): instance.save() return post_save.connect(instance_post_save, sender=ProductA) |