【发布时间】:2013-11-04 16:52:41
【问题描述】:
我认为我需要创建“多对多通用关系”。
我有两种参与者:
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
【问题讨论】:
-
我个人更喜欢使用 ForeignKey 而不是 GenericForeignKey 来获得通过 ORM 获得的额外功能。
-
@schillingt 感谢您的回复。奖励可以是 SingleVoucherReward 或 MultiVoucherReward,参与者可以是 MemberParticipant 或 FriendParticipant。这意味着如果我选择标准 FK,我需要 4 个 FK,其中两个总是空白。这对我来说是糟糕的数据库设计,所以我认为 GenericForeignKey 更有意义,但我愿意接受建议。我对您的评论“获得了额外的功能”感兴趣,您使用 GenericForeignKey 会失去什么?
-
您不能再在过滤器或排除中使用这些字段。在docs 的本节底部提到了它。
-
当然我仍然可以通过参与者对象直接在 ParticipantReward 上搜索?
-
当然可以,只是稍微复杂一些,因为您必须同时过滤participant_content_type 和participant_object_id,而不是单个对象。
标签: python django django-models