3

I have two models and want to create a field for the second class that is a concatenation of a foreign field and a field within the model.

The code I have so far is:

class Drug(models.Model):
    drug_name = models.CharField("Drug Name", max_length=200)
    reference_title = models.CharField("Publication Title",max_length=1024)
    pub_date = models.DateField("Pubication Date",'date published')
    pubmed_link = models.CharField("PubMed Link", max_length=300)

class Risk(models.Model):
    drug_link = models.ForeignKey(Drug, on_delete=models.CASCADE)    
    dosage = models.IntegerField(default=0)
    independent_risk = models.DecimalField("Individual Risk", max_digits=4, decimal_places=2)

I want to add a new field to the Risk model that is automatically populated by a concatenation of the selected value for drug_link and the entered value for dosage.

GeeJay
  • 141
  • 1
  • 3
  • 12

2 Answers2

7

This can be accomplished by a python property on the class:

class Risk(models.Model):
    drug_link = models.ForeignKey(Drug, on_delete=models.CASCADE)    
    dosage = models.IntegerField(default=0)
    independent_risk = models.DecimalField("Individual Risk", max_digits=4, decimal_places=2)

    @property
    def name_dosage(self):
         return "%s - %s" % ( self.drug_link.drug_name, self.dosage )
Community
  • 1
  • 1
2

If you do not need to store this value in database but rather use it in templates, you would not need to create extra fields. You can use methods like this:

class Risk(models.Model):
    drug_link = models.ForeignKey(Drug, on_delete=models.CASCADE)    
    dosage = models.IntegerField(default=0)
    independent_risk = models.DecimalField("Individual Risk", max_digits=4, decimal_places=2)

    def dosages(self):
        return "{} - {}".format(self.drug_link.drug_name, self.dosage) 

And in the templates, you can just do:

{% for risk in risks %}
    {{ risk.dosage }}
{% endfor %}
masnun
  • 11,635
  • 4
  • 39
  • 50