Search code examples
pythondjangodjango-modelsforeign-keys

Django - forloop in model.py to assign foreignkey


I have two models - User and Rank. During def save() I want the Users Rank automatically assigned to a Rank depending on the points the user has and the min_points from the Rank model.

Models

class User(AbstractUser):
    points = models.IntegerField(default=0)
    rank = models.ForeignKey(Rank, on_delete=models.SET_NULL, null=True, blank=True)


class Rank(models.Model):
    rank = models.CharField(max_length=200)
    min_points = models.IntegerField()

Now I added save() function to User model to check the user points and compare to the correct Rank

# ...user model
def save(self, *args, **kwargs):
    for i in Rank.objects.all():
        if self.points >= i.min_points:
            self.rank == Rank.objects.get(id=i.id)
    super().save(*args, **kwargs)

Unfortunally nothing happend after saving or creating a new user.

My IDE throw warning: Unresolved attribute reference 'objects' for class 'Rank'

Do I miss something? I cant figure out the issue...


Solution

  • There is no need to enumerate over the Rank objects. We can retrieve the Rank with the largest amount of min_points that is less than or equal to the self.points with:

    def save(self, *args, **kwargs):
        self.rank = Rank.objects.filter(
            min_points__lte=self.points
        ).latest('min_points')
        return super().save(*args, **kwargs)