1

So I have a model in Django that represents affiliates. The user receives a commission for each referral they get. How much the referrer receives depends on their user level. The user level depends on how many referrals they have. Under 5 referrals = Basic, under 10 referrals = Intermediate, under 15 referrals = Advanced.

How can I code the model so the user level is automatically determined by the amount of referrals an affiliate has? Lets say

class Affiliate(models.Model):
    user= models.OneToOneField(User)
    affiliate_id = models.PositiveIntegerField(primary_key=True)
    referral_id = models.PositiveIntegerField(blank=False, null=False)
    user_level = (
('B', 'Basic'),
('I', 'Intermediate'),
('A', 'Advanced'),
 default='B')
    referred_by = models.ForeignKey(referral_id, default=1)
4

1 回答 1

0

你不能。

django 模型(或它底层的数据库)是静态数据。做出运行时决策是模型方法的用途:

class Affiliate(model.Model):
    affiliate_id = models.PositiveIntegerField(primary_key=True)
    …

    def user_level(self):
        levels = [(5, 'B'), …]
        for referrals, category in levels:
             if self.some_field < referrals:
                 return category 

Model 方法的好处在于它们的行为类似于框架其余部分中的 Model 字段。目前尚不清楚您的 Affiliate 模型是否有可用的推荐计数,因此我使用some_field了它。根据您希望此查找的数据驱动方式,它可能需要自己的模型。

django 教程的第一部分涵盖了模型方法,这让我相信关于它们的问题已经很普遍了。

于 2013-10-03T02:42:29.163 回答