Django: Add and Subtract from inventory in models

做~自己de王妃 提交于 2020-01-11 14:21:50

问题


I'm trying to do something that I thought would be simple, but it has proven a bit challenging for me right now.

I am trying to build a simple ATM system for Banknotes in Django 1.11 and Python 3.6.

I basically need to keep track of banknotes that are in stock and how many of each kind. But I realized that using the logic that I'm accustomed with I only create new instances of the model instead of adding to the quantity fields.

I know how to use a quantity field to add items of an order (but thats also creating a new instance of an order), but how can I do it to make changes to an inventory without creating a new instance of it?

I guess it should have something to do with ManyToManyField and the through argument. I'm also not sure if I should separate each Banknote as one Class or put them all under a single Class.

Any ideas?

Here's my model:

class Cedula(models.Model):
    um          = models.IntegerField(blank=False, default=0)
    dois        = models.IntegerField(blank=False, default=0)
    cinco       = models.IntegerField(blank=False, default=0)
    dez         = models.IntegerField(blank=False, default=0)
    vinte       = models.IntegerField(blank=False, default=0)
    cinquenta   = models.IntegerField(blank=False, default=0)
    cem         = models.IntegerField(blank=False, default=0)

    class Meta:
        verbose_name = "Cédula"
        verbose_name_plural = "Cédulas"

回答1:


Everything looks fine in your model. You will have just a single row which will get be updated after it gets created first.

Firstly create the object of Cedula

from app.models import Cedula
cedula = Cedula()
cdeula.save() # This will instantiate the row with all entries 0.

For updating you have to perform this

from app.models import Cedula
from django.db.models import F
cedula = Cedula.objects.all()[0]
cedula.dios = F('dios')+ 2 # Here adding 2 or any number which you want to update with
cedula.vinte = F('vinte') -5 # Here subtracting with 5 or again number which you want to update with
cedula.save()

Usually for the models which don't have much relational things to do or single entries in them it is best to create their object in a seprate start script and run them before running your server. So that database can populate the content before.



来源:https://stackoverflow.com/questions/45042424/django-add-and-subtract-from-inventory-in-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!