Django ORM。如何保存()新值?
如何保存()新值 错误:AttributeError:'int'对象没有属性'save' 我有以下代码:Django ORM。如何保存()新值?,django,django-models,django-orm,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.
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'
您只需更改为:
mp.save()
相反
mp
是MagzinProduct
类的一个实例,而mp.quantity
只是一个int
,它没有save
方法。要更新实例,请在此实例上调用save()
,在本例中,它只是mp.save()
您不保存属性,而是保存实例。在您的示例中,在mp
实例上调用save方法,类似于mp.save()
,这将保存该对象的所有属性。请参阅以供参考