elemolotiv
elemolotiv

Reputation: 181

how to initialise a peewee.Model object? __init__() doesn't work

I am not able to initialise the fields of a "peewee.Model" descendant object with the usual init() method. How can I initialise alternatively?

import peewee

peewee_database = peewee.SqliteDatabase('example.db')

class Config():

    def __init__(self, seats, cylinders):
        self.seats = seats
        self.cylinders = cylinders

class Car(peewee.Model):

    magic_number = peewee.IntegerField()
    color = peewee.TextField()

    class Meta:
        database = peewee_database

    def __init__(self, config):
        self.magic_number = config.seats / config.cylinders
        self.color = None

peewee_database.connect()
peewee_database.create_tables([Car])

config = Config(7, 6)
car = Car(config)
car.color = "blue"
car.save()

produces this error in Python3:

  File "test.py", line 27, in <module>
    car = Car(config)
  File "test.py", line 20, in __init__
    self.magic_number = config.seats / config.cylinders
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 3764, in __set__
    instance.__data__[self.name] = value
  TypeError: 'NoneType' object does not support item assignment

help! :)

Upvotes: 5

Views: 1652

Answers (2)

elemolotiv
elemolotiv

Reputation: 181

the Peewee author was so kind to answer himself. I think using a factory method is the cleanest solution, to avoid conflicting with the way peewee uses __init()__

You can still put it in __init__() with the caveat that __init__() is going to be called not just when instantiating objects yourself, but also every time a Car instance is read from a database cursor. I think you probably could make a classmethod on your Car object and use that as a factory for complex logic?

Refer to this.

Upvotes: 1

shadow
shadow

Reputation: 885

what you doing is kinda wrong. u can separate class Car that peewee use for database management and use other class like "class ACar():" to create your object car and after that u can save your data in database by calling Car.get_or_create(magic_number=car.magic_number , color=car.color). see peewee documentation about creating record. because the way you are using is wrong. you are saving car that is and object of Car and not the module that peewee suppose to return it to you after using Car.get_or_none(...). even if you will use save, u need to use it in record that already exist in database. if u want to create new record use create(), and it's a class methode ( mean, Car.create()). hope this gives you and idea about how to re-write your code. even if you want one class Car, use Car.create(...) to create your record and not the object, if you already have a record, the object car = Car() it's not right, the right way it car = Car.get_or_none('your parameters'). Car.get_or_create(...) will create a record if not exist, see documentation

Upvotes: 0

Related Questions