我有一個計劃模型,可以有2個獎勵分配給它只有一個爲該計劃的成員和另一個爲他們的朋友。Django模型設計使用GenericForeignKey
以下是我如何爲此設計模型,但現在我開始質疑設計,Scheme和獎勵鏈接是否不正確?我是否應該以抽象獎勵的方式建立關係?
方案:
class Scheme(models.Model):
name = models.CharField(max_length=60)
participant_reward_content_type = models.ForeignKey(ContentType,
editable=False,
related_name='%(app_label)s_%(class)s_as_participant',
null=True, blank=True
)
participant_reward_object_id = models.PositiveIntegerField(null=True, blank=True)
participant_reward = generic.GenericForeignKey('participant_reward_content_type', 'participant_reward_object_id')
friend_reward_content_type = models.ForeignKey(ContentType,
editable=False,
related_name='%(app_label)s_%(class)s_as_friends',
null=True, blank=True
)
friend_reward_object_id = models.PositiveIntegerField(null=True, blank=True)
friend_reward = generic.GenericForeignKey('friend_reward_content_type', 'friend_reward_object_id')
獎勵:
class AbstractReward(models.Model):
"""
Abstract reward common information shared for all rewards.
"""
description = models.CharField(max_length="150")
active = models.BooleanField(default=True)
#scheme = models.ForeignKey(Scheme, null=True,)
class Meta:
abstract = True
class SingleVoucherReward(AbstractReward):
"""
Single-use coupons are coupon codes that can only be used once
"""
pass
class Meta:
app_label = 'schemes'
class MultiVoucherReward(AbstractReward):
"""
A multi-use coupon code is a coupon code that can be used unlimited times.
"""
code = models.CharField(max_length=200)
expiry = models.DateTimeField(null=True)
class Meta:
app_label = 'schemes'
class CustomReward(AbstractReward):
"""
A reward class used when it can't be handled or they would like to
handle reward fulfillment themselves.
"""
pass
class Meta:
app_label = 'schemes'
感謝DaveB,你的評論非常有趣,現在閱讀了Django的兩個Scoops。 – Prometheus
這個方法我唯一的問題是不同的獎勵有擴展的屬性,不必與每個相關。這就是爲什麼我有一個基地的抽象模型。我喜歡使用選擇器的想法。 – Prometheus
代理模型,這很有趣我不知道你甚至可以做到這一點,很好。唯一的問題是這個「必須從一個非抽象模型類繼承」 – Prometheus