[Answer]-How do I clone a model field in another model in Django?

1๐Ÿ‘

I assume you want to copy it rather than reference it. So that if in future price of medicine changes, past bills does not change.

So you can add a similar field in Bill and implement pre_save signal to put same price as medicine object.

class Bill(models.Model):
    regid = models.ForeignKey(Patient)
    medicine_name = models.ForeignKey(Medicine)
    quantity = models.IntegerField()
    price = models.IntegerField(max_length=30)

@receiver(pre_save, sender=Bill, dispatch_uid="my_unique_identifier")
def signal_price_populate(sender, **kwargs):
    try:
        inst = kwargs['instance']
        inst.price = inst.machine_name.price
    except Exception:
        #something not right
๐Ÿ‘คRohan

0๐Ÿ‘

Since you already have Medicine as a ForeignKey you could access the price through this relationship. ie.

medicine_name__price

However, if you want a field directly linked to the value of price then you can use a further specification of a ForeignKey.

class Bill(models.Model):
    regid = models.ForeignKey(Patient)
    medicine_name = models.ForeignKey(Medicine)
    quantity = models.IntegerField()
    price = models.ForeignKey(Medicine, to_field="price")

UPDATE after more info:

If you are wanting to set the price field in the Bill model based on the price value in the Medicine model on save of the Bill model you could either do this at the save of the model or of the form. This is assuming that your medicine_name foreignkey is working properly so that we can call the value of the price through this relationship.

class Bill(models.Model):
    regid = models.ForeignKey(Patient)
    medicine_name = models.ForeignKey(Medicine)
    quantity = models.IntegerField()
    price = models.IntegerField(max_length=30)
    def save(self, *args, **kwargs):
        self.price = self.medicine_name.price
        super(Bill, self).save(*args, **kwargs)
๐Ÿ‘คjondykeman

Leave a comment