I'm wirting a query using Django, I have my model:
class Recommender(models.Model):
customer = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="recoCustomer")
brand = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="recoBrand")
recommender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="recommender")
authorized = models.ForeignKey(State, default=5,
help_text=_('Recommend state (5-pending, 6-approved, 2-canceled).'),
)
dateTime = models.DateTimeField(auto_now=True)
The first requeriment was:
I need all records where the customer is equal to loggued in user and
authorizedis equal to5. My first query was:Recommender.objects.all().filter( customer=request.user, authorized=State.objects.get(pk=5) )
However, right now I need all records where the customer is equal to loggued in user and authorized is equal to 5 , but if exist a couple (brand_id, customer_id) where authorized is equal to 6 , the query must ignore the anothers records of the couple (brand_id, customer_id) with authorized is equal to 5.
------------------------------------------------------------------
Records on table Recommenders
------------------------------------------------------------------
| authorized | brand_id | customer_id | recommender_id | dateTime |
|------------|----------|-------------|----------------|----------|
| 5 | 1 |32 |31 | ... |
| 5 | 1 |32 |19 | ... |
| 5 | 9 |32 |8 | ... |
| 5 | 28 |32 |8 | ... |
| 6 | 1 |32 |8 | ... |
In the previous table, the query should not return records with couple (brand_id, customer_id) = (1, 32), because exist one record with this couple with authorized equal to 6.
How Can I to make this query using Django ORM?
Q(). You can do differentQ()that take parameters like yourfilter()and then combine them using&,|,~.