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

1

6

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
Rover answered 12/9, 2014 at 21:0 Comment(0)
E
4

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.

Euhemerus answered 13/9, 2014 at 20:42 Comment(1)
Thanks. Can you add a comment about the creator? I would like to create my own def __init__(file_name, convert_to_black_and_white=False, [...]), but that would break the Peewee constructor.Rover

© 2022 - 2024 — McMap. All rights reserved.