简体   繁体   中英

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(...)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM