How can I fill in a row or add a second table? I need to perform calculations with the last row from the first table and send the results to the second table. This is something reminiscent of processing data in two DataFrame .
How can I add a table of values to the model after performing calculations on the data from the last row from another table model?
Or is this only possible with the participation of the DataFrame functionality?
class Model_1(models.Model):
name_1 = models.IntegerField()
name_2 = models.IntegerField()
name_3 = models.IntegerField()
name_4 = models.IntegerField()
class Model_2(models.Model):
name_5 = models.IntegerField()
name_6 = models.IntegerField()
queryset = Model_1.objects.all()
values_m1 = queryst.name_1 * queryst.name_2 / queryst.name_3 - queryst.name_4
queryset = Model_2.objects.all()
values_m2 = queryst.name_5 = values_m1
CodePudding user response:
One way would be to perform the calculations using the queryset, and then create a new instance of Model_2 with the calculated values and save it.
queryset = Model_1.objects.all()
last_row = queryset.last()
values_m1 = last_row.name_1 * last_row.name_2 / last_row.name_3 - last_row.name_4
new_entry = Model_2(name_5=values_m1)
new_entry.save()
The second option would be to use the Django ORM to perform the calculations and insert the data in a single query.
from django.db.models import F
Model_2.objects.create(name_5=F('name_1')*F('name_2')/F('name_3')-F('name_4'))
CodePudding user response:
You can have two choices to sync two tables together.
- Using the Django
post_save
signals. In this approach, you set apost_save
for the first table, and then, you will update the second table every time thing is saved on the first table.
from django.db.models.signals import post_save
from django.dispatch import receiver
class Model_1(models.Model):
name_1 = models.IntegerField()
name_2 = models.IntegerField()
name_3 = models.IntegerField()
name_4 = models.IntegerField()
class Model_2(models.Model):
name_5 = models.IntegerField()
name_6 = models.IntegerField()
# method for updating
@receiver(post_save, sender=Model_1)
def update_stock(sender, instance, **kwargs):
# Do the calculation Here to update the model 2
- Using Postgres triggers. This approach would be implemented on your database and no python code would run. Everything would is managed in the database.