Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python - Django - Add the value of new entry to an existing value when another object of same name is added to the table

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 enter image description here

enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...