[Django]-How to set Value of One field of Django model equal to Other field of other Django model

7👍

You don’t actually need to maintain two fields with the same value.

I’d define a method on MainModel and get the timestamp from the related model:

class MainModel(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
            verbose_name='Email Address',
            max_length=255,
            unique=True)
    payment_online = models.ForeignKey(OnlinePayments, null=True, blank=True)
    ...

    def get_purchase_date(self):
        return self.payment_online.timestamp if self.payment_online else None
👤alecxe

1👍

I think @alecxe provided a great answer.
However, if you really want to store the information in 2 places you can override the save method on the OnlinePayments model so that whenever a record is saved on that model, you can manually save the timestamp value to purchase_date in MainModel.

Add the following save method to your OnlinePayments model (filling in the purchase_date assignment under the comment)

def save(self, *args, **kwargs):
    # save the value of self.timestamp into purchase_date

    super(OnlinePayments, self).save(*args, **kwargs)

Leave a comment