I'm fairly new to Django, hence open for any kind of suggestions
I have two models Order and Stock
My code:
models.py
class Order(models.Model):
idorder = models.AutoField(db_column='idorder', primary_key=True)
date_ordered = models.DateField(db_column='Date_Ordered', blank=True, null=True) # Field name made lowercase.
number_ordered = models.IntegerField(db_column='Number_Ordered', blank=True, null=True) # Field name made lowercase.
idproduct = models.ForeignKey(Product, models.DO_NOTHING, blank=True, db_column='idProduct', verbose_name='Product Name') # Field name made lowercase.
idsupplier = models.ForeignKey(Supplier, models.DO_NOTHING, blank=True, db_column='idSupplier', verbose_name='Supplier Name') # Field name made lowercase.
class Meta:
managed = False
db_table = 'order'
class Stock(models.Model):
idstock = models.AutoField(primary_key=True)
quantity = models.IntegerField(db_column='Quantity', blank=True, null=True) # Field name made lowercase.
idproduct = models.ForeignKey(Product, models.DO_NOTHING, db_column='idProduct', verbose_name='Product Name', blank=True) # Field name made lowercase.
idorder = models.ForeignKey(Order, models.DO_NOTHING, db_column='idOrder', verbose_name='Order Name', blank=True)
class Meta:
managed = False
db_table = 'stock'
def __str__(self): #to return supplier_name for foreign key references
return self.idproduct.product_name
I have implemented the addition of corresponding Order object into Stock table using signals
#this signal is to add object to stock automatically when order object is created
def create_stock_item(sender, instance, created, **kwargs):
if created:
s = Stock(
idorder=instance,
quantity=instance.number_ordered,
idproduct=instance.idproduct
)
s.save()
post_save.connect(create_stock_item, sender=Order)
When I add an Order, the corresponding Stock object is created
What I want to achieve is that when I add another entry for Teddy Bear in the Order table, I want the quantity field for Teddy Bear in the Stock table to be the sum of old entry and new entry instead of creating a new entry.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…