通过一个抽象模型

2024-09-29 19:18:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个抽象模型:

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模型来连接DistributorLink。但由于through模型不能将抽象模型作为外键,我不知道该怎么办。我是否需要为DistributorPersonDistributorGroup创建两个独立的through模型,或者有一种方法可以通过1 through模型来实现这一点。另外,我不知道我的2 m2m inLink模型是否是实现我想要的行为的合适方法。你知道吗

所以我想知道用抽象模型来组织这些m2m模型的方法是什么。你知道吗


Tags: 方法模型truemodelmodelspassclassgroups
1条回答
网友
1楼 · 发布于 2024-09-29 19:18:48

第一个问题是DistributorPersonDistributorGroup是否真的需要成为独立的表。如果它们非常相似,那么只使用一个表可能是有意义的。(例如,如果要对电话号码进行建模,则可能不会使用单独的Home、Work和Mobile表,而是使用带有type字段的单个表。)

(请注意,可以使用proxy models允许不同的Django模型共享同一个数据库表。)

如果确实需要单独的表,那么可以查看GenericForeignKey。这是一种允许外键引用不同模型类型的对象的机制。在您的情况下,这可能看起来像:

class DistributorGroup(Distributor):
    distributor_links = GenericRelation(DistributorLink, related_query_name="distributor_groups")

class DistributorPerson(Distributor):
    distributor_links = GenericRelation(DistributorLink, related_query_name="distributor_persons")

class Link(models.Model):
    pass

class DistributorLink(models.Model):
    link = models.ForeignKey(Link);

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

请参阅generic relations上的文档以获取示例和更多详细信息。你知道吗

最后,如果其他方法都失败了,您确实可以为这两种关系创建两个独立的M2M表。你知道吗

请注意,这些都与抽象模型无关。抽象模型只是Django中代码重用的一种机制,它们不会影响表或在其上运行的查询。你知道吗

相关问题 更多 >

    热门问题