我有一个抽象模型:
class Distributor(models.Model):
class Meta:
abstract = True
以及继承它的两个模型:
class DistributorGroup(Distributor):
pass
class DistributorPerson(Distributor):
pass
我还有一个llink模型:
class Link(models.Model):
distributors_persons = models.ManyToManyField(
'people.DistributorPerson', blank=True, related_name='distributors_persons_of_links')
distributors_groups = models.ManyToManyField(
'groups.DistributorGroup', blank=True, related_name='distributors_groups_of_links')
链接可以与其中一个分销商建立关系。我通过添加2个m2m并将blank=True
设置到这两者来完成这个行为。你知道吗
现在我意识到我需要一个through
模型来连接Distributor
和Link
。但由于through
模型不能将抽象模型作为外键,我不知道该怎么办。我是否需要为DistributorPerson
和DistributorGroup
创建两个独立的through
模型,或者有一种方法可以通过1 through
模型来实现这一点。另外,我不知道我的2 m2m inLink
模型是否是实现我想要的行为的合适方法。你知道吗
所以我想知道用抽象模型来组织这些m2m模型的方法是什么。你知道吗
第一个问题是
DistributorPerson
和DistributorGroup
是否真的需要成为独立的表。如果它们非常相似,那么只使用一个表可能是有意义的。(例如,如果要对电话号码进行建模,则可能不会使用单独的Home、Work和Mobile表,而是使用带有type字段的单个表。)(请注意,可以使用proxy models允许不同的Django模型共享同一个数据库表。)
如果确实需要单独的表,那么可以查看
GenericForeignKey
。这是一种允许外键引用不同模型类型的对象的机制。在您的情况下,这可能看起来像:请参阅generic relations上的文档以获取示例和更多详细信息。你知道吗
最后,如果其他方法都失败了,您确实可以为这两种关系创建两个独立的M2M表。你知道吗
请注意,这些都与抽象模型无关。抽象模型只是Django中代码重用的一种机制,它们不会影响表或在其上运行的查询。你知道吗
相关问题 更多 >
编程相关推荐