Skip to content Skip to sidebar Skip to footer

Django: How To Access The Previous Model Class Instances While Creating New Instance Of The Same Class?

I have a model in my django app like below: models.py class Profit(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) month = models.Cha

Solution 1:

As stated in the comments one should generally not store things in the database that can be calculated from other data. Since that leads to duplication and then makes it difficult to update data. Although if your data might not change and this is some financial data one might store it anyway for record keeping purposes.

Firstly month as a CharField is not a very suitable field of yours for your schema. As firstly they are not easily ordered, secondly it would be better for you to work with a DateTimeField instead:

classProfit(models.Model):
    month = models.CharField(max_length=100) # Remove this
    made_on = models.DateTimeField() # A `DateTimeField` is better suited
    amount = models.IntegerField()
    total_profit = models.IntegerField()

Next since you want to print all the Profit instances along with the total amount you should use a Window function [Django docs] which will be ordered by made_on and we will also use a frame just in case that the made_on is same for two entries:

from django.db.models import F, RowRange, Sum, Window

queryset = Profit.objects.annotate(
    total_amount=Window(
        expression=Sum('amount'),
        order_by=F('made_on').asc(),
        frame=RowRange(end=0)
    )
)

for profit in queryset:
    print(f"Date: {profit.made_on}, Amount: {profit.amount}, Total amount: {profit.total_amount}")

Post a Comment for "Django: How To Access The Previous Model Class Instances While Creating New Instance Of The Same Class?"