gpt4 book ai didi

python - Django 多对多通用关系

转载 作者:太空狗 更新时间:2023-10-29 17:40:23 26 4
gpt4 key购买 nike

我认为我需要创建一个“多对多通用关系”。

我有两种类型的参与者:

class MemberParticipant(AbstractParticipant):
class Meta:
app_label = 'participants'


class FriendParticipant(AbstractParticipant):
"""
Abstract participant common information shared for all rewards.
"""
pass

这些参与者可以有 1 个或多个 2 种不同的奖励(奖励模型来自另一个应用程序):

class SingleVoucherReward(AbstractReward):
"""
Single-use coupons are coupon codes that can only be used once
"""
pass

class MultiVoucherReward(AbstractReward):
"""
A multi-use coupon code is a coupon code that can be used unlimited times.
"""

所以现在我需要将这些全部联系起来。这就是我考虑建立这种关系的方式(见下文)这行得通吗,您看到任何问题吗?

建议的链接模型如下:

class ParticipantReward(models.Model):


participant_content_type = models.ForeignKey(ContentType, editable=False,
related_name='%(app_label)s_%(class)s_as_participant',
)
participant_object_id = models.PositiveIntegerField()
participant = generic.GenericForeignKey('participant_content_type', 'participant_object_id')


reward_content_type = models.ForeignKey(ContentType, editable=False,
related_name='%(app_label)s_%(class)s_as_reward',
)
reward_object_id = models.PositiveIntegerField()
reward = generic.GenericForeignKey('reward_content_type', 'reward_object_id')

注意:我使用的是 Django 1.6

最佳答案

鉴于您现有的表,您的方法是完全正确的方法。虽然没有官方消息( this discussion ,在 2007 年涉及核心开发人员,但似乎没有任何进展),我确实找到了这个 blog post它采用相同的方法(并在第三方库中提供),还有一个流行的答案 here这是相似的,除了关系的只有一侧是通用的。

我想说这个功能从未进入 django 主干的原因是虽然它是一个罕见的需求,但使用现有工具很容易实现。此外,想要自定义“直通”表的可能性可能相当高,因此大多数最终用户实现无论如何都会涉及一些自定义代码。

唯一可能更简单的方法是拥有基本的参与者和奖励模型,以及它们之间的多对多关系,然后使用 multi-table inheritance将这些模型扩展为成员(member)/ friend 等。

最终,您只需要权衡通用关系的复杂性与将对象的数据分布在两个模型之间的复杂性。

关于python - Django 多对多通用关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com