我设置了我的模型,以便在将商品添加到商店时,它会根据计数为其提供自己的店内ID。我称之为SPI。加法功能正常,它可以正确分配正确的SPI。但我在删除功能方面遇到了麻烦。当从表中删除一个对象时,我需要它来遍历剩余的对象并将它们的SPI设置为少一个。但是我一直收到错误StoreLiquor matching query does not exist. Lookup parameters were {'StoreLiquorID': 7, 'storeID': <Store: test store>}
我没有正确地进行查询吗?
模特:
class Store(models.Model):
StoreID = models.AutoField(primary_key=True)
user = models.ManyToManyField(User)
StoreName = models.CharField('Store Name', max_length=30)
(other things here too but probably not necessary for this case)
class StoreLiquor(models.Model):
StoreLiquorID = models.AutoField(primary_key=True)
liquorID = models.ForeignKey(Liquor)
storeID = models.ForeignKey(Store)
StorePrice = models.DecimalField('Store Price', max_digits=5, decimal_places=2)
SPI = models.PositiveIntegerField('SPI', max_length=10)
观点:
def delete(request, liquor_id, store_id):
storeID = Store.objects.get(StoreID=store_id)
StLiquor = StoreLiquor.objects.get(storeID=store_id, StoreLiquorID=liquor_id)
LiqSPI = StLiquor.SPI
SPIcount = StoreLiquor.objects.filter(storeID=store_id).count()
for newSPI in range(LiqSPI, SPIcount):
newStLiquor = StoreLiquor.objects.get(storeID=storeID, StoreLiquorID=newSPI)
newStLiquor.SPI = newSPI-1
StLiquor.delete()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
答案 0 :(得分:1)
而不是for
循环,请将queryset.update与django.db.models.F
一起使用:
from django.db.models import F
...
StoreLiquor.objects.filter(storeID=storeID, SPI__gt=LiqSPI).update(SPI=F('SPI')-1)