0

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 authorized is equal to 5. 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?

1
  • 1
    You need Q() . You can do different Q() that take parameters like your filter() and then combine them using &, |, ~. Commented Apr 5, 2018 at 16:42

1 Answer 1

1

Here is a sample of Q()

    if query:
        queryset_find = queryset_list.filter(
            Q(FP_Item__contains=query))
        context = {'object_list': queryset_find}
        return render(request, 'index.html', context)

If you need multiple Queries here is the reference, search within for "multiple" https://docs.djangoproject.com/en/2.0/topics/db/queries/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.