Y
Y
Yura Khlyan2015-11-26 18:13:58
Django
Yura Khlyan, 2015-11-26 18:13:58

How to update the number of products after saving the form?

Good day, dear connoisseurs)
There is a product. It is sold in two stores with one warehouse. The model has a "quantity in stock" field, but it needs to be the same for two stores. In the admin panel (Django-Oscar), I removed the ability to directly edit the quantity of goods in stock for an individual store. Instead, I added a new field in which you need to enter how many goods to add.
I thought to solve it like this:

  • add a new add_to_stock attribute to the product model
  • add an update_stock method that would do num_in_stock += add_to_stock
  • run method for all stores every time a product is saved

I'm stuck on the third point. Can you help me decide? Or are there other, better solutions?
I'm using Django-Oscar 1.2 and Django 1.8
P.S. Sorry for my bad Russian
P.P.S. Admin view:
a347de5b14db430b9e041b24a412de60.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yura Khlyan, 2016-01-29
@MAGistr_MTM

Solution:
As advised, the quantity of goods in the warehouse was placed in a separate field for the goods (and prices are stored in stockrecord). In stockrecord, the quantity is made a reference to the quantity of the product.

class Product(AbstractProduct):
    ...
    num_in_stock_product = models.PositiveIntegerField(
        _("Number in stock(product)"), blank=True, null=True)
    stock_update = models.IntegerField(
        _("Stock update"), blank=True, null=True)

    def save(self, *args, **kwargs):
        if self.stock_update:
            if not self.num_in_stock_product:
                self.num_in_stock_product = 0
            self.num_in_stock_product += self.stock_update
        self.stock_update = None
        super(AbstractProduct, self).save(*args, **kwargs)
        self.attr.save()

class StockRecord(AbstractStockRecord):
     ...
    @property
    def num_in_stock_stockrecord(self):
        return self.product.num_in_stock_product
        
    @property
    def net_stock_level(self):
        """
        The effective number in stock (eg available to buy).

        This is correct property to show the customer, not the num_in_stock
        field as that doesn't account for allocations.  This can be negative in
        some unusual circumstances
        """
        all_allocations = 0
        for stockrecord in self.product.stockrecords.all():
            if stockrecord.num_allocated is not None:
                all_allocations += stockrecord.num_allocated
        if self.num_in_stock_stockrecord is None:
            return 0
        return self.num_in_stock_stockrecord - all_allocations

Well, I redid the forms / views / etc. for the new field num_in_stock_stockrecord (was num_in_stock)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question