is it possible to write if conditions inside models and if yes how?

Viewed 72

this is my models and i am trying to assign category automatically if the user gets a marks greater than 10 he will get "legendary" category else "gold" category

class Intrest(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="uuser")
    marks=models.IntegerField(default=0)
    choices = (
        ('Legendary', "Legendary"),
        ('Gold', "Gold"),
    )
    category=models.CharField(max_length=10,choices=choices,blank=True,null=True)

    def value(self):
        if self.marks==10:
            self.category="Legendary"
        else:
            self.category="gold"


    @property
    def __str__(self):
         return f"{self.user}"

I have made a value function but its not working can anyone tell me how can I achieve this?

2 Answers

Yes, it is possible: you need to use @property decorator:

@property
def category(self):
    """Returns category depending of mark."""
    if self.marks==10:
        self.category="Legendary"
    else:
        self.category="Gold"
    

You can override the model save() method:

class Intrest(models.Model):
    ...

    def save(self, *args, **kwargs):
        if self.marks > 10:
            self.category = "Legendary"
        else:
            self.category = "Gold"
        super().save(*args, **kwargs)
Related