click
click

Reputation: 2113

Django : Query a model from it's save method

I want to override the save method in a model and from inside the save method, query the model itself. Can I access the Student model inside it's own method like it's done below?

class Student(models.Model):
    action = models.CharField(max_length=50)    
    count  = models.IntegerField()

    def save(self, *args, **kwargs):
        count = Student.objects.filter(action=self.action).order_by('-count'))[:1]
        if count:
            #do something
        else:
            #do something else
        super(Student, self).save(*args, **kwargs)

What's the difference between these 2 ways?

count = Student.objects.filter(...)
count = self.__class__.objects.filter(...)

Upvotes: 2

Views: 1166

Answers (1)

Jiaaro
Jiaaro

Reputation: 76898

1st question: Yes you can access a class in one of it's methods.

2nd question: In your example they are equivalent, but if you were to subclass it (called SubStudent for example), the first would still reference Student where self.__class__ would reference SubStudent

Upvotes: 4

Related Questions