[Django]-Make model field equal concatenation of two fields in Django

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 )

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 %}

Leave a comment