0

I have started a simple entry-level django project for practicing, it uses sql-server as the database (mssql-django).

How can I have a derived attribute (calculated column) from a different table as a field on my model?

Let's say I have this model

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)
    birth_date = models.DateField()

class JobTitles(models.Model):
    job_title = CharField(max_length=20)

class Jobs(models.Model):
    job_id = models.OneToOneField(
        JobTitles,
        on_delete=models.CASCADE,
    )
    person_id = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
    )
    job_income_in_usd = models.IntegerField()

class Salary(models.Model):
    person_id = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
    )
    name = 'SELECT name FROM Person WHERE Salary.person_id = Person.id'
    income_in_euro = 'SELECT job_income_in_usd * 0.89 FROM Jobs INNER JOIN Salary ON Salary.person_id=Jobs.person_id'
    age = 'SELECT datediff(year, (SELECT birth_date FROM Person WHERE Salary.person_id=Person.id), getdate())'

How do I implement the above SELECT codes in Python-Django codes?

Related questions:

Derived attribute in Django model

How to add a calculated field to a Django model

Django getting field names from different models

Related SQL-Server question:

How to create derived attribute?

Shayan
  • 709
  • 1
  • 15
  • 31
  • Instead of a `raw sql` script, can you provide a pratical example of what you whant, with class and instance if possible. – Rvector Nov 21 '21 at 18:44

1 Answers1

1

You can use @property decorator for that, to give you an example:

class Salary(models.Model):
    person_id = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
    )
    
    @property
    def name(self):
        return self.person_id.name if self.person_id else None

    @property
    def income_in_euro(self):
        if not self.person_id:
           return
        return Jobs.objects.filter(person_id_id=self.person_id_id).first(). job_income_in_usd * 0.89

btw i do not think its a good idea naming your ForeignKeys with _id at the end.

aberkb
  • 664
  • 6
  • 12