django模型保存错误'对象没有属性“field_id”

时间:2012-11-28 10:23:26

标签: django model foreign-keys

我有一个带有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个字段 - idshipping_rate_iddate_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'

1 个答案:

答案 0 :(得分:2)

正如评论中所提到的,会话中有一个旧实体在添加新字段之前被腌制。