Django 查询集每月显示值

Django queryset to show values every month

我正在做一个Django APP(必填)计算每个月的盈亏

我想在 N 个月 中加入一项功能,您将支付 value/N(即: 100/5 美元,相当于每月 20 美元)。

此功能就像一个银行 APP 显示您尚未支付的金额(即:从本月到 10 月)

顺便说一句,损失只有一个记录(我尽量不改变这个)

目前一切顺利,但记录 仅出现在我搜索的月份 (查看下方)以及当我尝试使用时:

Account.objects.filter(date__year__gte=y) or Account.objects.filter(date__month__gte=m)

Account.objects.filter(date__year__lt=y) or Account.objects.filter(date__month__lt=m)

记录显示整年或大于或小于保存月份的月份(没有过滤,所以如果是从七月到十一月,它会显示到十二月或一月)

View.py

def account(request, pk):
search = f"{datetime.now().year} - {datetime.now().month:02}"
account = Account.objects.get(id=pk)
ctx = {
    'search': search
}
if request.GET.get('month'):
    search = request.GET.get('month')
    y, m = search.split('-')
    ctx.update({
        'search': search
    })
    date_loss = filter_by_model_date(Loss, m, y)
    date_profit = filter_by_model_date(Profit, m, y)
    profit = filter_by_account(date_profit, account)  
    loss = filter_by_account(date_loss, account)  
    ctx.update({
         'profit': profit, 'loss': loss
    })
return render(request, 'account/account.html', ctx)

Functions.py

def filter_by_model_date(model, month, year):
    """
    Filter by Model by month and year
    """
    return model.objects.filter(date__month=month, date__year=year)

def filter_by_account(model, field):
    """
    Logs Filter by account
    """
    return model.filter(account=field)

Models.py

class Account(models.Model):
    name = models.CharField(max_length=200)

class Profit(models.Model):
    [...]
    value = models.FloatField()
    date = models.DateField(default=datetime.today)
    account = models.ForeignKey(Account, on_delete=models.CASCADE)

class Loss(models.Model):
    [...]
    months = models.IntegerField()
    value = models.FloatField()
    date = models.DateField(default=datetime.today)
    account = models.ForeignKey(Account, on_delete=models.CASCADE)

所以没有任何错误消息,我只是想在我的应用程序中添加该功能,这是一种使 N 个月损失从保存月份到最后一个月出现的方法。

我试过逆向,用timedelta挽救上个月的Loss,但是逆向不行,我挣扎着不挽回同一条记录N次

所以我设法使用列表来做到这一点...它并不复杂(我不知道它是否是 pythonic)但我是这样做的,而且它正在工作!

感谢所有试图回答我的问题的人,我将我的代码放在这里,供所有想要开发这样的应用程序的人使用!

我只想说一件事:“祝你好运,永不放弃!”

View.py

def account(request, pk):
search = f"{datetime.now().year} - {datetime.now().month:02}"
account = Account.objects.get(id=pk)
ctx = {
    'search': search
}
if request.GET.get('month'):
    search = request.GET.get('month')
    y, m = search.split('-')
    ctx.update({
        'search': search
    })
    date_loss = filter_by_model_date(Loss, m, y)
    date_profit = filter_by_model_date(Profit, m, y)
    profit = filter_by_account(date_profit, account)  
    loss = filter_by_account(date_loss, account)  
    ctx.update({
         'profit': profit, 'loss': loss
    })

    list_month = check_is_month(Loss, account, y, m) # Added this line of code

        data.update({
            'month': list_month
        })

return render(request, 'account/account.html', ctx)

Functions.py

def check_is_month(model, field, year, month):
    """
    Return a list with all the losses 
    """
    buy_loss = filter_by_model_account(model, field)
    list_loss = []
    for b in buy_loss: #Run through the filter
        if get_date_iso_format(year, month) >= b.date: #If the b.date is lesser or equal the search, this if not to show in earlier months (P.S: Had to transform in isoformat)
            list_loss.append(b) #Append the record
            final_date = check_final_date(b.date, c.months) #Get Final Date
            m = (int(month) - b.date.month) #Get The number of months (Just for show)
            if final_date > replace_month_year(get_date_iso_format(year, month), month, year): # If Final date is greater than the month searched (P.S: Had to transform in isoformat)
                if m > 0: #Another just for show
                    b.months = f"{m}/{b.months}"
                else:
                    b.months = f"{m + 12}/{b.months}"
                b.date = replace_month_year(b.date, month, year) #Change the date like a Bank APP
            elif final_date < replace_month_year(get_date_iso_format(year, month), month, year): #If the date is less 
                list_loss.remove(b)
    return list_loss


def get_date_iso_format(year, month):
    """
    Return String date year/month/01
    """
    return datetime.fromisoformat(f"{year}-{month}-01").date()

def replace_month_year(date, month, year):
    """
    Replace function
    """
    return date.replace(month=int(month), year=int(year))


def check_final_date(date, months):
    """
    Return final date
    """
    return date + timedelta(seconds=months* 30 * 24 * 60 * 60)

def filter_by_model_account(model, field):
    """
    Filter by Model and Account
    """
    return model.objects.filter(account=field)

在模板中,您可以运行通过亏损、盈利和月份,做我的客人,做任何你想做的事!