Friday, 13 September 2013

django loop threw objects and change there values

django loop threw objects and change there values

I have my model set up so that when a liquor is added to a store, it gives
it it's own in-store ID based on the count. I've called this the SPI. The
addition function works fine, it properly assigns the correct SPI. But I'm
having trouble with the delete function. When an object is deleted from
the table, I need it to loop through the remaining objects and set there
SPI to one less. However I keep getting an error StoreLiquor matching
query does not exist. Lookup parameters were {'StoreLiquorID': 7,
'storeID': <Store: test store>} Am I not doing the query correctly?
The models:
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)
The view:
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'))

No comments:

Post a Comment