Wednesday, June 27, 2018

Queryset calculation and then filter/exclude/limit data rendered

I have a small checkbook application where I store transactions (expenses and income) amounts by date.  I render these to a template using python to add the cumulative balance prior to render.  This work fine for my little application, but not too sure how scalable it will be over time.


My goal is to have this displayed by month with the running balance.  I first researched custom pagination, but found nothing on date pagination by month and year.  I then started down the road of excluding data from the the queryset in the for loop which is easy in other languages, but this also seemed to be a no go.  My current thought is to exclude the data from the queryset in the for loop and move the data into a dictionary or list, or json.


Any advice for me?  Right now I need all objects from the Check model to get an accurate balance and then I need to filter that to limit the records by month.


Finally, I did tried to filter the check_list after the balance was added, but found out that does not work as the query goes back to the model and I loose the balance.


Here is my model


class Check(models.Model):

    """

    Model representing a checkbook transaction.

    """

    check_type = (('CR', 'credit'),('DR', 'debit'),('SV', 'savings'),('DT', 'debt reduction'),)

    

    dater = models.DateField(help_text=' .the date of the transaction')

    type = models.CharField(max_length=2, choices=check_type, help_text=' .credit or debit')

    category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True)

    name = models.CharField(max_length=100, help_text=' .description')

    amount = models.IntegerField(default=0, help_text=' .amount')

    cleared = models.BooleanField(help_text=' .cleared with the bank?')

    created = models.DateTimeField(auto_now_add=True)


Here is my function view


def checkbookList(request):

    check_list = Check.objects.all()

    #checks = Check.objects.all()

   

    balance = 0

    #for chk in checks:

    for chk in check_list:

        balance += chk.amount

        chk.balance = balance


        if chk.cleared:

            chk.cleared = '\u221A'

        else:

            chk.cleared = '-'


    return render(request, 'checkbook/checkbook.html', {'checks': check_list})


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3db2052a-ba54-4f20-adca-ed42126c5b92%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment