Home > front end >  Django many-to-many override save method to increment a field instead of creating new objects
Django many-to-many override save method to increment a field instead of creating new objects

Time:01-28

I have the following classes in my Models.py:

class Size(models.Model):
    prod_size = models.DecimalField(max_digits=3, decimal_places=1)
    quantity = models.IntegerField(default=1)

    def save(self, *args, **kwargs):
        size_exists = Size.objects.filter(
             prod_size=self.prod_size, product_id=self.product_id
        ).exists()
        if size_exists:
           Size.objects.filter(
               prod_size=self.prod_size, product_id=self.product_id
           ).update(quantity=F('quantity') 1)
        else:
           super(Size, self).save(*args, **kwargs)

class Product(models.Model):
    sizes = models.ManyToManyField(Size, related_name='products')

I want the save method to update the quantity field of Size if there already exists a prod_size with the same value and related to the same product_id. But I am having trouble with getting the product_id information from the intermediate table. Is there any way I can achieve this?

CodePudding user response:

A better way to do this is -

class Product(models.Model):
    product_code = models.charfield(unique=True)

class Size(models.Model):
    product = models.ForeignKey(Product)
    prod_size = models.DecimalField(max_digits=3, decimal_places=1)
    quantity = models.IntegerField(default=1)

    class Meta:
        unique_together = (
            ("product ", 'prod_size '),
        )

Now sizes are linked to each product, which means for a product you can have many sizes, and also in the size models you can not have duplicate product_size with respect to each product (meta property).

Now in your views check whether a product_size is available for the given product or not. If product_size is not there do a create or else update the quantity.

  •  Tags:  
  • Related