Complex query in Django ORM

-1

I have the following table with the following records:

|id | datetime | state_id | brand_id | customer_id | recommender_id |
|---|----------|----------|----------|-------------|----------------|
| 1 | ...      |   5      |     1    |     32      |       31       |
| 2 | ...      |   5      |     1    |     32      |       19       |
| 3 | ...      |   5      |     9    |     32      |       8        |
| 4 | ...      |   5      |     28   |     32      |       8        |
| 5 | ...      |   6      |     1    |     32      |       8        |


The entity in the model is called Recommender . brand_id and customer_id are foreign keys of User .

And I'm designing a query using Django 2 that returns all the records where the customer_id is equal to the logged user ( request.user ) and the state is equal a 5. This is my query and it works:

recommend = Recommender.objects.all().filter(
  customer=request.user, authorized=State.objects.get(pk=5)
)

The previous query returns all the records in state 5 (with customer = request.user ).
However, I need that when a pair (brand_id, customer_id) has state 6 (like the last record in the previous table), I do not return in the query no record of that couple in state 5.

How could I make that query using the Django ORM?

    
asked by CarMoreno 05.04.2018 в 16:42
source

1 answer

0

You can make a condition (if) with a previous search that tells you if there is a Recommender that with state 6 with the fields for which you want to filter, if it exists, you do not filter.

Example:

if not Recommender.objects.filter(customer=request.user, brand = brand, state=6).exist():
    recommend = Recommender.objects.all().filter(
        customer=request.user, authorized=State.objects.get(pk=5))

You can also get both those with state = 5 and state = 6 and then pass it through the if. This second form will make the function slower.

    
answered by 06.04.2018 в 13:01