简体   繁体   中英

Query Django model based on relationship between ForeignKey sub elements

class Price(models.Model):
    date = models.DateField()
    price = models.DecimalField(max_digits=6, decimal_places=2)
    product = models.ForeignKey("Product")

class Product(models.Model):
    name = models.CharField(max_length=256)
    price_history = models.ManyToManyField(Price, related_name="product_price", blank=True)

I want to query Product such that I return only those products for whom the price on date x is higher than any earlier date.

Thanks boffins.

As Marcin said in another answer, you can drill down across relationships using the double underscore syntax. However, you can also chain them and sometimes this can be easier to understand logically, even though it leads to more lines of code. In your case though, I might do something that would look this:

first you want to know the price on date x:

a = Product.objects.filter(price_history__date = somedate_x)

you should probably test to see if there are more than one per date:

if a.count() == 1:
    pass
else:
    do something else here

(or something like that)

Now you have your price and you know your date, so just do this:

b = Product.objects.filter(price_history__date__lt = somedate, price_history__price__gt=a[0].price)

know that the slice will hit the database on its own and return an object. So this query will hit the database three times per function call, once for the count, once for the slice, and once for the actual query. You could forego the count and the slice by doing an aggregate function (like an average across all the returned rows in a day) but those can get expensive in their own right.

for more information, see the queryset api:

https://docs.djangoproject.com/en/dev/ref/models/querysets/

You can perform a query that spans relationships using this syntax:

Product.objects.filter(price_history__price = 3)

However, I'm not sure that it's possible to perform the query you want efficiently in a pure django query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM