Varun Chadha
Varun Chadha

Reputation: 376

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

Hi i am Setting the value of one field of my Django model equal to value of other field of Other model. This value should change dynamically.

This is my first 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)
    register_date = models.DateTimeField(default=datetime.now, blank=True)
    purchase_date = models.CharField(max_length=32, default='')
    is_csr = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

This is second model

class OnlinePayments(models.Model):

    payer_email = models.CharField(max_length=255, default=None, null=True)
    payer_name = models.CharField(max_length=255, default=None, null=True)
    timestamp = models.DateTimeField(auto_now_add=True, blank=True)

    def __str__(self):
        return self.payer_email

i want to set the value of purchase_date in MainModel equal to value of timestamp in OnlinePayments.

Any help would be appericiated

Upvotes: 3

Views: 3894

Answers (2)

sfletche
sfletche

Reputation: 49714

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)

Upvotes: 1

alecxe
alecxe

Reputation: 473833

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

Upvotes: 7

Related Questions