I'm having trouble adding the column of a table created by Python and the peewee module:
This is how I created the table:
from peewee import SqliteDatabase, Model, CharField
db = SqliteDatabase('coches.db')
class Coche (Model):
Marca = CharField()
Modelo = CharField()
Precio = CharField()
Numero_vendidos = CharField()
Gama = CharField()
class Meta:
database = db
db.connect()
db.create_tables([Coche]) #el modelo de datos, lo que va a contener
db.close()
and in another python file I have added my data:
from Modulo_10.exe1 import Coche
listado_coches_tupla = [
('Ford', 'Fiesta', '9000', '1000', 'Baja'),
('Ford', 'Focus', '14500', '540', 'Media'),
('Ford', 'Mondeo', '28000', '630', 'Alta'),
('Citroen', 'C3', '9500', '780', 'Baja'),
('Citroen', 'C4', '13500', '340', 'Media'),
('Citroen', 'C5', '26000', '120', 'Alta'),
('Peugeot', '208', '9700', '1250', 'Baja'),
('Peugeot', '308', '16000', '160', 'Media'),
('Peugeot', '408', '27500', '1760', 'Alta')
]
Coche.insert_many(listado_coches_tupla, fields=[Coche.Marca, Coche.Modelo, Coche.Precio,
Coche.Numero_vendidos, Coche.Gama]).execute()
Once created, I try to add the Numbers Sold column with this function:
for coche in Coche.select(Coche.Numero_vendidos):
valor=sum(int(coche.Numero_vendidos))
print(valor)
I can't print the total value of the sum so it gives me this error:
valor=sum(int(coche.Numero_vendidos))
TypeError: 'int' object is not iterable
I'm new to this language and would like to know where I'm going wrong
Thanks in advance
Well, the operation
sum()
is a reduce operation , that is, you have a set of numbers, for example a list, and you add all the numbers that are in that list, for example:Departure:
10
What happens to you is that
coche.Numero_vendidos
it is not a collection , it is a simple number that represents the number of cars sold. So it's like you're doing:Departure:
TypeError: 'int' object is not iterable
I get the same error as you, since the number five is not a collection of N elements in which you add x1 +x2 +x3 .... xn , but it is a simple number, so the error in Spanish would:
"I can't iterate through an integer"
Solution
Once you get here, what you can do is store the quantities of the different cars in a list using the method
.append()
, and then apply the functionsum()
to said list: