Using one query set for another query

28 views
Skip to first unread message

lone...@gmail.com

unread,
Mar 28, 2023, 9:56:58 PM3/28/23
to Django users
Hello all,

    I am trying to use the query of:
paid_bills = bill_payment_history.objects.filter(date_paid__year='2023', date_paid__month='03')

as criteria for another query to only show the unpaid bills.

The known_bills model is my control list of known bills that occur frequently.
The  bill_payment_history model is my bill transaction table.  It is a running history of transactions for bill payment.

A sample of known_bills records is:
bill_1
bill_2
bill_3

A sample of  bill_payment_history is:
bill_1 paid last month
bill_2 paid last month
bill_3 paid last month
bill_1 paid this month
bill_2 paid this month
bill_3 paid this month

What I am trying to do is use bill_payment_history filtered on date_paid by year and month and query the known_bills table to see what bills have not been paid yet.  I keep trying something similar to:  results = paid_bills.exclude(short_description__in=known_bills)

but my results either keep coming up with all of the records or none of them.  What am I doing wrong?

Here is the model information:

class known_bills(models.Model):
    #Full bank transaction
    description = models.CharField(max_length=255)
    #String value to search the CSV file with.
    short_description = models.CharField(max_length=255, unique=True)
    #Value I know it as.
    friendly_name = models.CharField(max_length=255)
    expected_due_date = models.DateField()
    expected_cost = models.DecimalField(max_digits=6,decimal_places=2)

class bill_payment_history(models.Model):
    description = models.CharField(max_length=255)
    short_description = models.ForeignKey(known_bills, on_delete=models.CASCADE)
    friendly_name = models.CharField(max_length=255)
    date_paid = models.DateField()
    cost = models.DecimalField(max_digits=6,decimal_places=2)

    class Meta:
        unique_together = (
            ('short_description',
            'date_paid'),
            )

Harsh Vyas

unread,
Apr 9, 2023, 4:24:16 PM4/9/23
to Django users
Hi,
Need a slight justification on your case what exactly is the use case you need to resolve.
So far, I understood you need to know details about unpaid bills, 

Approach 1:- 
Model bill_payment_history will have data for field date_paid in case of only paid bills, so you can try 
to query something like

queryset= bill_payment_history.objects.filter(date_paid= None)

Approach 2:- 
You can annotate a field on all known_bills object using case statement for
 which different between current date and excepted_due_date is already breached.

For annotate and case refer to below docs:-

Hope this solve your use case
Reply all
Reply to author
Forward
0 new messages