Negative Stock Prevention

50 views
Skip to first unread message

tech george

unread,
Aug 29, 2022, 10:19:28 AM8/29/22
to django...@googlegroups.com
Hello,

Please help crack the below code, I want to prevent negative stock, and if the stock is == 0, deduct it from reorder_level instead.
Currently, the stock goes negative.

models.py
class Stock(models.Model):
quantity = models.IntegerField(default='0', blank=True, null=True)
reorder_level = models.IntegerField(default='0', blank=True, null=True)
class Dispense(models.Model):
drug_id = models.ForeignKey(Stock, on_delete=models.SET_NULL,null=True,blank=False)
dispense_quantity = models.PositiveIntegerField(default='1', blank=False, null=True)
taken=models.CharField(max_length=300,null=True, blank=True)

views.py
try:  

if request.method == 'POST':
if form.is_valid():
username = form.cleaned_data['taken']
qu=form.cleaned_data['dispense_quantity']
ka=form.cleaned_data['drug_id']
# print(username)



stock= eo=Stock.objects.annotate(
expired=ExpressionWrapper(Q(valid_to__lt=Now()), output_field=BooleanField())
).filter(expired=False).get(id=username)
form=DispenseForm(request.POST or None, instance=stock)
instance=form.save()
# print(instance)
if quantity > 0
instance.quantity-=qu
instance.save()
else:
instance.reorder_level-=qu
instanc.save()

form=DispenseForm(request.POST or None ,initial={'patient_id':queryset})
form.save()

messages.success(request, "Drug Has been Successfully Dispensed")

return redirect('manage_patient_pharmacist')
else:
messages.error(request, "Validity Error")

return redirect('manage_patient_pharmacist')

context={
"patients":queryset,
"form":form,
# "stocks":stock,
"drugs":drugs,
"prescrips":prescrips,
"expired":ex,
"expa":eo,

}
if request.method == 'POST':

print(drugs)
context={
"drugs":drugs,
form:form,
"prescrips":prescrips,
"patients":queryset,
"expired":ex,
"expa":eo,

}
except:
messages.error(request, "Dispensing Not Allowed! The Drug is Expired ,please do a re-stock ")
return redirect('manage_patient_pharmacist')
context={
"patients":queryset,
"form":form,
# "stocks":stock,
"drugs":drugs,
"prescrips":prescrips,
"expired":ex,
"expa":eo,

}

return render(request,'templates/discharge.html',context)

Derek

unread,
Aug 30, 2022, 9:30:33 AM8/30/22
to Django users
As a start, the logic checks for the model should not be in views.py but rather with the model object (in models.py).  You can extend the save() method, for example, and add the checks there.

See: 

Ryan Nowakowski

unread,
Aug 30, 2022, 10:44:51 AM8/30/22
to django...@googlegroups.com
On Mon, Aug 29, 2022 at 05:18:39PM +0300, tech george wrote:
> Please help crack the below code, I want to prevent negative stock, and if
> the stock is == 0, deduct it from reorder_level instead.
> Currently, the stock goes negative.
>
> models.py
>
> class Stock(models.Model):
> quantity = models.IntegerField(default='0', blank=True, null=True)
> reorder_level = models.IntegerField(default='0', blank=True, null=True)
>
> class Dispense(models.Model):
> drug_id = models.ForeignKey(Stock,
> on_delete=models.SET_NULL,null=True,blank=False)
> dispense_quantity = models.PositiveIntegerField(default='1',
> blank=False, null=True)
> taken=models.CharField(max_length=300,null=True, blank=True)

Maybe change quantity and reorder_level to PositiveIntegerField?

Thomas Couch

unread,
Aug 30, 2022, 11:08:36 AM8/30/22
to Django users
I don't see where you define the quantity variable, should that be instance.quantity? Also, presumably you want to check if quantity is greater than or equal to qu rather than 0.
Try changing `if quantity > 0` to `if instance.quantity >= qu`

tech george

unread,
Aug 31, 2022, 6:58:36 AM8/31/22
to django...@googlegroups.com
Hello,

Sorry for the late reply.

I changed the models as below and added checkConstraint , But when I migrate I get the below error.

What am I still doing wrong?

class Stock(models.Model):
    quantity = models.PositiveIntegerField(default='0', blank=True, null=True)
    reorder_level = models.PositiveIntegerField(default='0', blank=True, null=True)

class Meta:
        CheckConstraint(check=Q(quantity__gt=0), name='quantity')



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9ef2d260-7c1a-4ff1-95ca-c13ded5f9f7bn%40googlegroups.com.

Ryan Nowakowski

unread,
Aug 31, 2022, 8:45:46 PM8/31/22
to django...@googlegroups.com
I don't see any error. Did you forget to post it?

Ammar Mohammed

unread,
Aug 31, 2022, 11:10:05 PM8/31/22
to 'Rahul Chauhan' via Django users
I don't think you need that constraint after using the PositiveIntegerField .


tech george

unread,
Sep 1, 2022, 1:19:18 AM9/1/22
to django...@googlegroups.com
Hello,

Sorry the error is:

django.db.utils.IntegrityError: CHECK constraint failed: quantity



tech george

unread,
Sep 1, 2022, 2:58:34 AM9/1/22
to django...@googlegroups.com
I managed to remove the error,

I had a negative stock in my DB.

Thanks a lot for the help.

On that note, I was also trying to get the dispensed from stock

I was trying to do this but I don't think it can work since there is already a foreign key at Dispense model fetching drug_id from stock.

What's the best way out?

@property
def dispensed(self):
return (self.quantity - self.dispense.quantity)



subin

unread,
Sep 1, 2022, 2:37:25 PM9/1/22
to django...@googlegroups.com
Thanks for leaving a voicemail! We appreciate your patience and will get back to you by the end of the day.

subin

unread,
Sep 1, 2022, 2:38:17 PM9/1/22
to django...@googlegroups.com
Thank you for your immediate response.

subin

unread,
Sep 1, 2022, 2:42:22 PM9/1/22
to django...@googlegroups.com
We have received your message and will be in touch within

subin

unread,
Sep 1, 2022, 3:00:35 PM9/1/22
to django...@googlegroups.com
I will ok forward to meeting you on February 15.

subin

unread,
Sep 1, 2022, 3:11:52 PM9/1/22
to django...@googlegroups.com
Thanks for contacting XYZ Company! One of our sales reps will reach out to you shortly. Tap to browse our summer sale while you wait

--

Ryan Nowakowski

unread,
Sep 1, 2022, 7:27:31 PM9/1/22
to django...@googlegroups.com
If you get this error during migration you likely have some existing Stock rows in your database with quantity that is less than 0. If this site is in production already, you'll need to create a data migration to change your negative quantities to zero.

https://docs.djangoproject.com/en/4.1/topics/migrations/#data-migrations

If this project isn't in production yet, just delete your database and migrations and start from ground zero.
Reply all
Reply to author
Forward
0 new messages