Query question

17 views
Skip to first unread message

Lee Hinde

unread,
Aug 18, 2015, 12:56:56 AM8/18/15
to django...@googlegroups.com
Given this model, I want to find all ProductSale objects that have expired and where the Person doesn't have a later (unexpired) purchase of the same product.

class ProductSale(models.Model):
    product = models.ForeignKey(Product)
    person = models.ForeignKey(Person)
...
    date_expires = models.DateField(blank=True, db_index=True)
    

The closest I've gotten is in the shell where I get a values_list of person and product for expired and unexpired and then compare the two lists. That leaves me with a list of tuples, that (due to the size of the list, I think) I can't use in a query.extra. 

Any suggestions would be appreciated.

(and sorry for the lame subject. I couldn't think of a way to be both succinct and informative.)
Message has been deleted

Dheerendra Rathor

unread,
Aug 18, 2015, 4:46:01 AM8/18/15
to Django users
You should use 'F' expression from django.db.models
So your expression would be like: 
ProductSale.objects.all().filter(date_expires__lt = now().date).exclude(date_purchased__gt = F('date_expires'))

Which roughly translates to  
SELECT * FROM productsale WHERE date_expires < CURRENT_DATE AND NOT (date_purchased > date_expires)

in mysql. 
Reply all
Reply to author
Forward
0 new messages