2

I have a data Model and I want to save the value of amount and the value of total_amount method into payment method to have a record of payment into database.

** data/models.py **

class Data(models.Model):
    """ Model of Data"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    document = models.FileField(upload_to='documents/%Y/%m/%d')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    amount = models.DecimalField(default=0, max_digits=6, decimal_places=2,
                                 blank=True, null=True)

    def total_amount(self):
        return Data.objects.filter(user=self.user).aggregate(Sum('amount'))['amount__sum']


payment/models.py

class Payment(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()
    created = models.DateTimeField(auto_now=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)
    amount = models.DecimalField(default=0, max_digits=6, decimal_places=2,
                                 blank=True, null=True)

payments/views.py

def payment_create(request):
    user = request.user
    data = Data.objects.filter(user=user)
    if request.method == 'POST':
        form = PaymentCreateForm(request.POST)
        if form.is_valid():
            payment = form.save()

            return render(request,
                          'payments/created.html',
                          {'payment': payment})
    else:
        form = PaymentCreateForm()
        # template and context
        template = 'payments/create.html'
        context = {'form': form,
                   'data': data
                   }
    return render(request,
                  template,
                  context
                  )

1
  • I edit the question and put the views.py. I want to make the Data Model amount also save to the Payment method amount. Commented May 2, 2020 at 13:23

1 Answer 1

2

Signals are a good option to achieve something like this. Using a post_save signal you can call a function whenever a new Data has been created and you can create a Payment instance there:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Data)
def create_payment(sender, instance, created, **kwargs):
    if created:
        # instance points to the new Data object created
        Payment.objects.create(amount=instance.total_amount()) # and any extra data you need
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it's close to solve my problem. but what I want is when the user fill up the payment form the total amount from data.total_amount will automatic to save to payment amount.
you mean amount field for Data model or amount field for Payment models? you can do both in the signal. doesn't matter creating a new instance for another model or just updating the same instance using instance.amount = instance.total_amount() and then instance.save()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.