A
A
adrenalinruslan2021-08-25 12:28:25
Django
adrenalinruslan, 2021-08-25 12:28:25

How to filter records of related tables?

The situation is as follows, I want to get all the clients who have fulfilled the condition of at least one status.
A client can have a card, and a client's card can have several statuses with certain conditions.

I want to execute a query by type: Find clients, count the number of transactions (visits) for each client and filter out clients that have fulfilled the visits condition for at least one status (statuses).

There is 1 client in the database, this client has 10 transactions. If you run the code below, it returns 2 identical clients, but one has 10 transactions, and the other 20, how to fix this?

clients = Client.objects.not_deleted().annotate(
    visits=models.Count(
        'transactions', filter=models.Q(
            transactions__amount__gt=0
        )
    )
).filter(wallet__statuses__visits__lte=models.F('visits')).distinct()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question