Many to Many Exclude on Multiple Objects

Viewed 2018

I have the following models:

class Deal(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    retailer = models.ForeignKey(Retailer, related_name='deals')
    description = models.CharField(max_length=255)
    ...etc

class CustomerProfile(models.Model):
    saved_deals = models.ManyToManyField(Deal, related_name='saved_by_customers', null=True, blank=True)
    dismissed_deals = models.ManyToManyField(Deal, related_name='dismissed_by_customers', null=True, blank=True)

What I want to do is retrieve deals for a customer, but I don't want to include deals that they have dismissed.

I'm having trouble wrapping my head around the many-to-many relationship and am having no luck figuring out how to do this query. I'm assuming I should use an exclude on Deal.objects() but all the examples I see for exclude are excluding one item, not what amounts to multiple items.

When I naively tried just:

deals = Deal.objects.exclude(customer.saved_deals).all()

I get the error: "'ManyRelatedManager' object is not iterable"

If I say:

deals = Deal.objects.exclude(customer.saved_deals.all()).all()

I get "Too many values to unpack" (though I feel I should note there are only 5 deals and 2 customers in the database right now)

We (our client) presumes that he/she will have thousands of customers and tens of thousands of deals in the future, so I'd like to stay performance oriented as best I can. If this setup is incorrect, I'd love to know a better way.

Also, I am running django 1.5 as this is deployed on App Engine (using CloudSQL)

Where am I going wrong?

3 Answers
Related