kdmontero
kdmontero

Reputation: 5

How can I call/refer to another property in the same models in django

I am creating a web app for creating a proposal/quotation for machines or equipment. I have a models for QuotationItem which has these properties:

In my models.py:

class QuotationItem(models.Model):
    product = models.Charfield(max_length=30)
    quantity = models.PositiveIntegerField(default=1)
    description = models.CharField(max_length=200, null=True)
    line_number = models.PositiveIntegerField()
    tagging = models.CharField(max_length=50)

Now, I want the 2 properties (line_number and tagging) be connected. Example:

line_number = 1,
tagging = "Equipment - 1"

line_number = 2,
tagging = "Equipment - 2"

In short, I want to set the tagging property with a default value of f"Equipment - {line_number}"

I am expecting that part of the request.data is the line_number, and therefore, I want the tagging to have that above default value, if none was provided. Is there a way to do this in models? Or should I handle this in views?

Upvotes: 0

Views: 411

Answers (1)

user2390182
user2390182

Reputation: 73450

The default value as used in the field definition (even when you use a callable) has no access to the instance. You would have to override save or connect to the pre_save signal:

class QuotationItem(models.Model):
    # ...
    def save(self, *args, **kwargs):
        if not self.pk:  # initial creation
            self.tagging = f"Equipment - {self.line_number}"
        super().save(*args, **kwargs)

Upvotes: 1

Related Questions