user7120561
user7120561

Reputation:

How to set default value of model field from another model known field value?

I am new to Django and I am sure that this question has been asked before if it has been please link me in.

I will try and explain exactly what I mean through an example.

I have a biscuit/cookie tin and in my tin, I have packs of biscuits, chocolate circles (10 biscuits), vanilla wafers (15 biscuits), etc. I have made a model for the product (biscuit packs) that has contains the max number of biscuits per pack.

from Django.db import models

class Product(models.Model):
   barcode = models.CharField(max_length=200, primary_key=True)
   quantity = models.IntegerField()

I want to have another model that contains the actual packs. When you create a pack with current_quantity defaulting to the product's quantity and as each biscuit is removed it can be decreased until 0.

class Pack(models.Model):
   barcode = modes.ForeignKey(Product)
   current_quantity = models.IntegerField()

So how do I get the model to get the Pack current_quantity to be the same as Product's quantity by default?

If trying to do it in models is the wrong place to try and attempt this. I welcome better DRY KIS solutions.

Thank you for your time.

Upvotes: 1

Views: 1033

Answers (1)

Ajmal Noushad
Ajmal Noushad

Reputation: 946

You can override the save() method of Pack model, like this:

 class Pack(models.Model):
    barcode = modes.ForeignKey(Product)
    current_quantity = models.IntegerField()

    def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
        if not self.id:
           self.current_quantity = self.barcode.quantity
        return super(Pack, self).save()

The line if not self.id checks whether the object currently has an id which means if the object is new. So self.current_quantity = self.barcode.quantity will only be executed at object creation

Upvotes: 2

Related Questions