Django:如何在创建同一类的新实例时访问先前的模型类实例? [英] Django: How to access the previous model class instances while creating new instance of the same class?

查看:48
本文介绍了Django:如何在创建同一类的新实例时访问先前的模型类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的django应用中有一个模型,如下所示:

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.CharField(max_length=100)
    amount = models.IntegerField()
    total_profit = models.IntegerField()

现在,我想做的是,每当为该类创建一个新的实例/对象时,用户就为此投入 month amount 一个月,但我希望它还可以通过将过去所增加的所有利润相加来计算出用户在获得当前利润之前所获得的总利润.

Now, what I want to do is that whenever a new instance/object is created for this class, the user puts the month and the amount of profit for that month, But I want that it also calculates the total profit the user got up till the current profit, by adding all the profits that was being added in the past.

例如.

如果用户要添加4月的利润,则它将所有值添加到先前添加的对象(3月,2月,1月等)的 amount 字段中,然后放入它在 total_profit 字段中.这样用户可以看到每个新条目获得了多少 total_profit .

if the user is adding the profit for month April, then it add all the values in the amount field of previously added objects of (March, February, January and so on..) and put it in the field total_profit. So that the user can see how much total_profit he got at each new entry.

我正在打印利润列表的views.py如下:

My views.py where I am printing the list of profits is given below:

views.py

class ProfitListView(ListView):
    model = Profit
    template_name = 'client_management_system/profit_detail.html'
    context_object_name = 'profits'


    # pk=self.kwargs['pk'] is to get the client id/pk from URL
    def get_queryset(self):
        user = get_object_or_404(Client, pk=self.kwargs['pk'])
        return Profit.objects.filter(client=user)

客户端是我的models.py中的另一个模型, Profit 类通过ForeignKey

Client is the another model in my models.py to which the Profit class is connected via ForeignKey

我也不完全知道如何在此视图中使用窗口函数.

I also don't exactly know how to use window functions inside this view.

推荐答案

如注释中所述,通常不应将可以根据其他数据计算出的内容存储在数据库中.因为那样会导致重复,从而使更新数据变得困难.尽管如果您的数据可能不会更改并且这是一些财务数据,则无论如何都可以将其存储以用于记录目的.

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.

首先,将 month 用作 CharField 对于您的架构而言,这不是一个非常合适的字段.首先,它们不容易排序,其次,最好使用 DateTimeField :

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:

class Profit(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()

下一步,由于要打印所有 Profit 实例以及总数,因此应使用

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}")

这篇关于Django:如何在创建同一类的新实例时访问先前的模型类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆