Making a multi-table inheritance design generic in Django

前端 未结 2 1856
小鲜肉
小鲜肉 2020-12-19 16:21

First of all, some links to pages I\'ve used for reference: A SO question, and the Django docs on generic relations and multi-table inheritance.

So far, I have a mul

相关标签:
2条回答
  • 2020-12-19 16:38

    I have done something similar to method 2 in one of my projects:

    from django.db import models
    from django.contrib.contenttypes.models import ContentType
    
    class BaseModel(models.Model):
        type = models.ForeignKey(ContentType,editable=False)
        # other base fields here
    
        def save(self,force_insert=False,force_update=False):
            if self.type_id is None:
                self.type = ContentType.objects.get_for_model(self.__class__)
            super(BaseModel,self).save(force_insert,force_update)
    
        def get_instance(self):
            return self.type.get_object_for_this_type(id=self.id)
    
    0 讨论(0)
  • 2020-12-19 16:47

    It would be better to compose the models of an Item model and an ItemType model. Subclassing models sounds nice and is useful in a few edge cases, but generally, it is safest and most efficient to stick to tactics that work with your database, rather than against it.

    0 讨论(0)
提交回复
热议问题