我有一个带有 2 个可选字段的简单 django 模型。尝试保存模型时出现错误。
class Cart(models.Model):
shipping = models.ForeignKey(ShippingRate, blank=True, null=True)
date_created = models.DateTimeField(blank=True, null=True)
def save(self, *args, **kwargs):
if not self.date_created:
self.date_created = datetime.datetime.now()
super(Cart, self).save(*args, **kwargs)
使用简单视图保存购物车对象,我收到以下错误 -
'Cart' object has no attribute 'shipping_id'
super()
这是失败的呼吁。我已经查看了数据库,并且已经获得了字段'id'
,'date_created'
并且'shipping_id'
在我的桌子上。
我正在使用南管理我的数据库,并且我尝试过删除、迁移和替换字段,但这不起作用。这是一个奇怪的 - 我想我错过了一些明显的东西,但我还没有发现它..
更新
我尝试删除save()
覆盖,甚至换出字段(然后向南迁移)。我把这个shipping
领域换成了一个新shipping_rate
领域——
class Cart(models.Model):
shipping_rate = models.ForeignKey(ShippingRate, blank=True, null=True)
date_created = models.DateTimeField(blank=True, null=True)
这次我在保存时遇到了同样的错误,只是它是导致它的 date_created 字段。
'Cart' object has no attribute 'date_created'
和以前一样,我浏览了我的(postgres)数据库,我可以看到我期望的 3 个字段 - id
、shipping_rate_id
和date_created
.
更新 2
好的,我已将代码缩减为 -
#models
class Cart(models.Model):
shipping_rate = models.ForeignKey(ShippingRate, blank=True, null=True)
modified = models.DateTimeField(blank=True, null=True)
class Meta():
app_label = 'cart'
#views
def add_to_cart(request):
if 'cart' in request.session:
cart = request.session['cart']
else:
cart = Cart()
if not cart.pk:
cart.save()
return HttpResponse('ok')
还有我的回溯——
Traceback:
File "/Users/aidan/Environments/bbhq/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/aidan/Code/bbhq/bbhq/cart/views.py" in add_to_cart
71. cart.save()
File "/Users/aidan/Environments/bbhq/lib/python2.7/site-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Users/aidan/Environments/bbhq/lib/python2.7/site-packages/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/Users/aidan/Environments/bbhq/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/Users/aidan/Environments/bbhq/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
1575. query.insert_values(fields, objs, raw=raw)
File "/Users/aidan/Environments/bbhq/lib/python2.7/site-packages/django/db/models/sql/subqueries.py" in insert_values
170. value = getattr(obj, field.attname)
Exception Type: AttributeError at /cart/add_to_cart
Exception Value: 'Cart' object has no attribute 'shipping_rate_id'