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

tun*_*nak 3 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)
Run Code Online (Sandbox Code Playgroud)

我有从机构生成的模型,我想从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)
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*nce 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
Run Code Online (Sandbox Code Playgroud)

和许多人一样基本像这样:

following_company = models.ManyToManyField(Company, blank=True, null=True)
following_hc = models.ManyToManyField(Institution, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)