Search code examples
pythondjangopostgresqlmodelaffiliate

Representing Membership Levels Django Models


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)

Solution

  • You can't.

    A django Model (or the database underlying it) is static data. To make run-time decisions is what Model methods are for:

    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 
    

    The nice thing about Model methods is that they behave like Model fields in the rest of the framework. It isn't clear that your Affiliate model has a referral count available to it, so I used some_field in its place. Depending on how data-driven you want this lookup to be, it might warrant its own Model.

    The django tutorial covers Model methods in its first section, which makes me believe that questions about them have been quite common.