这是我的模型课:
class Product(BaseModel):
product_name = peewee.CharField(max_length=100, default="", index=True)
description = peewee.CharField(max_length=100, index=True)
price = peewee.DecimalField(max_digits=10, decimal_places=2)
quantity_in_stock = peewee.IntegerField(
constraints=[peewee.Check("quantity_in_stock >= 0")]
)
owners = peewee.ManyToManyField(Buyer, backref="owned_products")
tags = peewee.ManyToManyField(Tag, backref="product_tag")
这是我将产品添加到数据库的功能:
def populate_test_database():
example_user1 = models.Buyer.create(
username="Anita89",
name="Anita Aniton",
address="1987 March St",
billing_info="MasterCard",
)
example_user2 = models.Buyer.create(
username="Peter12",
name="Peter Peterson",
address="12 April St",
billing_info="Bank Account",
)
product1 = models.Product.create(
product_name="So",
description="Bar of soap",
price=12.99,
quantity_in_stock=50,
)
product3 = models.Product.create(
product_name="Shampoo",
description="Bottle of shampoo",
price=8.49,
quantity_in_stock=30,
)
product2 = models.Product.create(
product_name="Beer 0",
description="Beer in a bottle",
price=8.99,
quantity_in_stock=60,
)
product1.owners.add(example_user1)
product2.owners.add(example_user2)
tag1 = models.Tag.create(name="Tag1")
tag2 = models.Tag.create(name="Tag2")
product1.tags.add(tag1)
product1.tags.add(tag2)
product2.tags.add(tag2)
product3.tags.add(tag1)
transaction1 = models.Transaction.create(
user=example_user1,
product=product1,
date="2023-09-10",
products_purchased=5,
)
transaction2 = models.Transaction.create(
user=example_user2,
product=product2,
date="2023-09-11",
products_purchased=2,
)
print("Test data populated.")
product_name 未存储,这是我得到的结果:
-产品名称: -描述:一块肥皂 -价格:12.99 -库存数量:50
-产品名称: -描述:一瓶洗发水 -价格:8.49 -库存数量:30
有人可以看一下我的代码,看看他们是否可以帮助我吗?
https://github.com/evi8n/Betsys_webshop_assignment.git
我的导师说我应该将其设置为default =“”,但这违背了创建产品数据库的目的......
先谢谢你了^_^
艾薇
数据存储得很好,我认为您的代码中可能存在关于数据实际存储位置的混淆:
from peewee import *
db = SqliteDatabase(':memory:')
class Buyer(db.Model):
name = CharField()
class Tag(db.Model):
tag = CharField(unique=True)
class Product(db.Model):
product_name = CharField(max_length=100, default='', index=True)
description = CharField(max_length=100)
price = DecimalField(max_digits=10, decimal_places=2)
quantity_in_stock = IntegerField(constraints=[
Check('quantity_in_stock >= 0')])
owners = ManyToManyField(Buyer, backref='owned_products')
tags = ManyToManyField(Tag, backref='tagged_products')
db.create_tables([Product, Buyer, Tag, Product.owners.through_model,
Product.tags.through_model])
Product.create(
product_name='So',
description='Bar of soap',
price=12.99,
quantity_in_stock=50)
for p in Product.select():
print(p.product_name)
这会正确打印“So”。
在我的交易类中,我使用了产品的反向引用:product = peewee.ForeignKeyField(Product, backref="product_name")
不知何故,这与我的产品类中的product_name变量冲突。将此 backref 更改为 name_of_product 解决了问题。