Django:从模型中的库存中添加和减去 [英] Django: Add and Subtract from inventory in models
问题描述
我正在尝试做一些我认为简单的事情,但是现在对我来说已经证明有点挑战。
I'm trying to do something that I thought would be simple, but it has proven a bit challenging for me right now.
我正在尝试构建一个Django 1.11和Python 3.6中用于钞票的简单ATM系统。
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?
我想它应该与ManyToManyField和through参数有关。我也不确定是否应该将每张钞票分为一个类别,还是将它们全部归为一个类别。
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.
有什么想法吗?
这是我的模型:
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"
推荐答案
模型中的一切看起来都很好。您将只有一行,在第一次创建后将对其进行更新。
Everything looks fine in your model. You will have just a single row which will get be updated after it gets created first.
首先创建Cedula对象
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.
这篇关于Django:从模型中的库存中添加和减去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!