模型与抽象类的多对多关系

时间:2013-09-21 17:18:13

标签: python django django-models

我有以下models.py

class Institution(models.Model):
    name = models.CharField(_('Name'), max_length=150, db_index=True)
    slug = models.SlugField(_('Domain name'), unique=True)

class Company(Institution):
    type = models.PositiveSmallIntegerField()


class HC(Institution):
    type = models.PositiveSmallIntegerField()
    bed_count = models.CharField(max_length=5, blank=True, null=True)

我有从机构生成的模型,我想从Profile模型中遵循机构。

class Profile(models.Model):
    user = models.OneToOneField(User)
    about = models.TextField(_('About'), blank=True, null=True)
    following_profile = models.ManyToManyField('self', blank=True, null=True)
    following_institution = models.ManyToManyField(Institution, blank=True, null=True)
    following_tag = models.ManyToManyField(Tag, blank=True, null=True)

我希望与继承机构的所有模型建立M2M关系。有没有办法用Generic Relations做到这一点?

1 个答案:

答案 0 :(得分:6)

听起来你已准备好进行多态:

https://django-polymorphic.readthedocs.org

否则你必须单独添加它们,所以你的Institution模型看起来像这样:

class Institution(models.Model):
    name = models.CharField(_('Name'), max_length=150, db_index=True)
    slug = models.SlugField(_('Domain name'), unique=True)

    class Meta:
        abstract = True

and manytomany就像这样基本:

following_company = models.ManyToManyField(Company, blank=True, null=True)
following_hc = models.ManyToManyField(Institution, blank=True, null=True)