Django ORM。如何保存()新值?

时间:2012-10-11 10:02:48

标签: django django-models django-orm

如何保存()新值?

错误: AttributeError:'int'对象没有属性'save'

我有这段代码:

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'

2 个答案:

答案 0 :(得分:1)

您只需要更改为:

mp.save() 

代替。


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

答案 1 :(得分:1)

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