Search code examples
pythonpeewee

pee wee Meta subclass inheritance


I am trying to implement peewee in my python application, and when defining my classes like this:

import datetime
import peewee as pw
import acme.core as acme

adapter = pw.MySQLDatabase(
    acme.get_config(path='database.db'),
    host=acme.get_config(path='database.host'),
    port=int(acme.get_config(path='database.port', default=3306)),
    user=acme.get_config(path='database.user'),
    passwd=acme.get_config(path='database.password'))


class Model(pw.Model):
    """
    The base model that will connect the database
    """
    id = pw.PrimaryKeyField()
    created_at = pw.DateTimeField()
    updated_at = pw.DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = adapter


class ServerModule(Model):
    enabled = pw.BooleanField()
    ipaddr = pw.IntegerField()
    port = pw.IntegerField()

    class Meta(Model.Meta):
        db_table = 'module_server'

I get the following error:

Traceback (most recent call last):
  File "db.py", line 25, in <module>
    class ServerModule(Model):
  File "db.py", line 33, in ServerModule
    class Meta(Model.Meta):
AttributeError: type object 'Toto' has no attribute 'Meta'

I have tried basic python subclass inheritance and it works, but here it doesn't, someone can point me to the right direction ?


Solution

  • You don't need to inherit Meta class from parent Meta attribute. Meta.database and other attributes are inherited automatically. In your example:

    import datetime
    import peewee as pw
    import acme.core as acme
    
    adapter = pw.MySQLDatabase(
        acme.get_config(path='database.db'),
        host=acme.get_config(path='database.host'),
        port=int(acme.get_config(path='database.port', default=3306)),
        user=acme.get_config(path='database.user'),
        passwd=acme.get_config(path='database.password'))
    
    
    class Model(pw.Model):
        """
        The base model that will connect the database
        """
        id = pw.PrimaryKeyField()
        created_at = pw.DateTimeField()
        updated_at = pw.DateTimeField(default=datetime.datetime.now)
    
        class Meta:
            database = adapter
    
    
    class ServerModule(Model):
        enabled = pw.BooleanField()
        ipaddr = pw.IntegerField()
        port = pw.IntegerField()
    
        class Meta:
            db_table = 'module_server'