3

我有以下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)

我有从机构生成的模型,我想从配置文件模型中关注机构。

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 关系。有没有办法用通用关系做到这一点?

4

1 回答 1

8

听起来你已经准备好使用多态了:

https://django-polymorphic.readthedocs.org

否则,您必须单独添加它们,因此您的机构模型将如下所示:

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

和manytomany只是这样的基本:

following_company = models.ManyToManyField(Company, blank=True, null=True)
following_hc = models.ManyToManyField(Institution, blank=True, null=True)
于 2013-09-21T17:31:15.740 回答