Django: Get each user Invoices, Expenses, Withdrawals. (ORM) relationship

Viewed 244

I've been stuck for a couple of hours, and can't figure out the correct way to do it. So basically I know that looping is not a really good practice, because if we would have a lot of users, the system would start time outing. So my idea is to pick the correct way to get the things that I need.

This is our core scheme:

This is our core scheme

I need to make this kind of 'table', and these are the things that I need:

enter image description here

This is the thing that will be displayed in our Front-End, so for now, I only need to collect the correct data and pass it into our FE. We use celery tasks, so the timing is always set (Mondays at 6 PM for ex.)

This is what I've tried so far..

for user in User.objects.all():
    start_date = timezone.now() - timedelta(weeks=1)

    # How to loop correctly over every user and check for invoices??
    invoices = InvoiceItem.objects.select_related('invoice', 'invoice__operation_ptr_id')
    # invoices[0].operation_ptr_id ???

The looping for user in User.objects.all() should probably be replaced to annotate. How can I make the relationship to get invoices, withdrawals, expenses?

1 Answers

Try querying from the User instead of InvoiceItem models

I'm not sure what specifically you need to return to the frontend, but if needed, returning the actual values should be quite easy after doing some annotations

To get the number of invoices of a user try this:

from django.db.models import Count
User.objects.annotate(total_invoices=Count("invoices"))

As for withdrawals and expenses, it seems like those models don't have a relationship with the User model at all. I would suggest updating your models to add a relationship between them, and query them similarly like the query above.

I'm also making the assumption that User = Customer, since you didn't actually provide the Customer model in your other post.

Related