0

如何保存()新值?

错误: AttributeError:“int”对象没有属性“保存”

我有这个代码:

class Magazin(models.Model):
    owner = models.ForeignKey(User, related_name='user_magazin', verbose_name='Owner')
    name = models.CharField("Magazin_Name", max_length=30)
    products = models.ManyToManyField('Product', through='MagazinProduct', blank=True, null=True)

class MagazinProduct(models.Model):
    product = models.ForeignKey('Product')
    magazin = models.ForeignKey('Magazin')
    quantity = models.IntegerField()

我尝试这样的事情:

from magazin.product.models import *

In [2]: user = 2 #user id

In [3]: quantity = 4

In [4]: magazin = Magazin.objects.get(owner=user)

In [6]: mp = MagazinProduct.objects.get(magazin=magazin, product=1) #product=1 this is ID

In [8]: mp.quantity
Out[8]: 1

In  [9]: mp.quantity = quantity
In [10]: mp.quantity
Out[10]: 4

In [11]: mp.quantity.save()
---------------------------------------------------------------------------

AttributeError: 'int' object has no attribute 'save'
4

2 回答 2

1

您只需要更改为:

mp.save() 

反而。


mpMagzinProduct类的一个实例,mp.quantity只是一个int没有save方法的实例。要更新一个实例,你调用save()这个实例,在这种情况下它只是mp.save().

于 2012-10-11T10:06:50.403 回答
1

你不保存一个属性- 你保存一个实例。在您的示例中,您在mp实例上调用 save 方法,mp.save()这将保存该对象的所有属性。请参阅官方文档以供参考。

于 2012-10-11T10:08:25.137 回答