简体   繁体   中英

Django: using the manager of the child model from an abstract parent model

class PositionModel(models.Model):
    xpos = models.IntegerField()
    ypos = models.IntegerField()
    def relative(self, x, y):
        self.__class__.objects.filter(xpos = self.xpos + x,
                                      ypos = self.ypos + y)
    class Meta:
        abstract = True

This example allows you to inherit PositionModel in several different models, then use the relative(x,y) function to perform a query based on the model of the child.

Does Django have some other, preferred way to write functions in abstract models that use the child's manager?

Proxy Models are meant to add extra methods or funcionality to the models, without messing with the fields/db... but as you want to inherit this method on more than one model, and Proxy-models are connected to one non-abstract class only, and xpos + ypos are being inherited too, I guess an abstract class could be the best choice to do the job.

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