Iokanaan Iokan
Iokanaan Iokan

Reputation: 775

Same-value field in two different but related models

class Currency(models.Model):
    name = models.CharField(max_length=200)
    shortname = models.CharField(max_length=3)
    symbol = models.CharField(max_length=2)
    
class Client(models.Model):
    name = models.CharField(max_length=200)
    base_rate = models.DecimalField(decimal_places=2, max_digits=15)
    country = models.CharField(max_length=200)
    currency = models.ForeignKey(Currency, on_delete=models.PROTECT)

class Job(models.Model):
    title = models.CharField(max_length=200)
    start_date = models.DateField()
    rate = models.DecimalField(decimal_places=2, max_digits=15)
    client = models.ForeignKey(Client, on_delete=models.PROTECT)
    currency = models.ForeignKey(Currency, on_delete=models.PROTECT)

I have above classes. Job and Client classes are related via the client field in the Job class.

Both classes have a field called currency, which is related to the Currency class.

In the current setup, obviously a Client object and a Job object that belongs to a Client can have different currency values.

I want to tie these toghether so that the Job object always has the same currency value as the related Client object. How do I do this?

Upvotes: 0

Views: 29

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

It might be better to only store the currency in the Client model, and then derive this from the related client, we thus can implement this with:

class Job(models.Model):
    title = models.CharField(max_length=200)
    start_date = models.DateField()
    rate = models.DecimalField(decimal_places=2, max_digits=15)
    client = models.ForeignKey(Client, on_delete=models.PROTECT)
    
    @property
    def currency(self):
        return self.client.currency

If we thus use myjob.currency, we will retrieve the currency of the client. By design, it is thus impossible that the client has a different currency, since we each time derive it from that client.

Upvotes: 2

Related Questions