![](/img/trans.png)
[英]Python class Attribute Error even though attribute is in __init__
[英]Django Attribute Error: object has no attribute '__state' and removing __init__ from Class
我正在嘗試為示例Django應用程序“ webshop”創建模型,並且在理解問題根源時遇到了麻煩。
我將原始代碼留在這里是因為所做的更改相當大,但是請讓我知道它是否令人困惑,並且我將刪除早期的代碼和文本或以某種方式對其進行修改。 跳至“編輯”以查看當前進度
我擁有的models.py
是:
從django.db導入模型
class Product(models.Model):
def __init__(self, title, quantity, description, image_url=""):
title = models.CharField(max_length=255)
self.quantity = quantity
self.title = title
self.description = description
self.image_url = image_url
def sell(self):
self.quantity = self.quantity - 1
我想要使用的方法是使用類似以下內容對其進行初始化:
toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10)
我可以這樣稱呼
print(toy1.quantity)
print(toy1.title)
toy1.sell()
依此類推,但是執行toy1.save()
返回錯誤
AttributeError: 'Product' object has no attribute '_state'
搜尋問題后,我發現不建議在這里使用init ,但https://docs.djangoproject.com/en/1.11/ref/models/instances/#creating-objects中提供的替代方法利用邏輯,其中類函數的第一次調用與初始調用不同。
如果我面臨的問題是由於依賴__init__
,我如何才能擺脫它,同時仍然能夠使用toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10)
來初始化對象toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10)
還是我的問題完全不同?
編輯:
因此,經過一些嘗試之后,我的models.py
現在處於此階段:
從django.db導入模型
class Product(models.Model):
title = models.CharField(max_length=255)
description = models.CharField()
quantity = models.IntegerField(default=0)
image_url = models.CharField(default="")
@classmethod
def sell(cls, quantity):
quantity = cls(quantity=quantity)
quantity = quantity - 1
return quantity
較早的命令仍然有效,並且我不再在類函數中使用init ,因此這是一個開始! 我現在嘗試運行toy1.save()
時遇到另一種錯誤:
sqlite3.OperationalError: table webshop_product has no column named title
The above exception was the direct cause of the following exception:
django.db.utils.OperationalError: table webshop_product has no column named title
我正在嘗試查找表格在我的網上商店中的位置,但是無論該表格中是否應包含“標題”,均不應發生該錯誤。
我認為您嘗試創建的模型應如下所示:
class Product(models.Model):
title = models.CharField(max_length=255)
quantity = models.IntegerField()
description = models.TextField()
image_url = models.CharField(max_length=255, validators=[URLValidator()])
def sell(self):
self.quantity = self.quantity - 1
self.save()
Django負責實例化,因此您不需要__init__
位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.