Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add methods and attributes to a class derived from peewee.Model

Tags:

python

peewee

I am working on an app with Cherrypy and Peewee, and I would like to know if my approach is good or wrong and dangerous.

All the examples of Peewee classes that I found have only the Meta subclass and the <xxx>Field attributes. I have never found an example with helper methods or properties.

I tried to make my own, and it works!

It works very well and I find it convenient, but I am afraid that I'm getting into trouble.

So my question is: can I add as many properties and methods to my classes derived from the peewee.Model, so I can do cool things like in the snippet below?

Or are there limits and guidelines to what I can do?

class PeeweeModel(peewee.Model):
    class Meta:
        database = db

class TempFile(PeeweeModel):
    file_type = peewee.IntegerField()
    original_file_name = peewee.CharField()
    temp_file_name = peewee.CharField()

    DRAWING = 1
    PDF = 2

    def href(self, settings):
        if(self.file_type == DRAWING:
            return self.temp_file_name
        elif(self.file_type == PDF:
            if settings.show_pdf:
                return self.temp_file_name
            elif settings.show_bitmap:
                bitmap = TempFile.create_bitmap_from_pdf(self.temp_file_name)
                return bitmap.temp_file_name

    @staticmethod
    def create_bitmap_from_pdf(self, file_name):
        [...]

Edit:

I would appreciate a comment about the constructor.

For example, I would like to do both these:

tmp = TempFile(file_name)                            # and run my own constructor
tmp = TempFile(original_file_name=file_name, [...])  # and run Peewee's constructor
like image 269
stenci Avatar asked Oct 31 '22 17:10

stenci


1 Answers

Yes! Of course you can, by all means. Models are just normal python classes, so you can treat them as such and add methods, properties, attributes, etc.

like image 170
coleifer Avatar answered Nov 12 '22 22:11

coleifer