简体   繁体   中英

Django Queryset how to create such a query?

There are two tables Products and Price history It is necessary to display the latest price by date from the price history table. It will work on Sqlite, but I can't figure out how to do it through Queryset

SELECT name,max(date),price,price_discount FROM polls_products
INNER JOIN polls_history_price on polls_history_price.product_id = polls_products.id
GROUP BY polls_products.id


class Products(models.Model):
    id = models.IntegerField(primary_key=True, blank=True)
    name = models.CharField(max_length=250)
    date_create = models.DateTimeField('Event Date')

class HistoryPrice(models.Model):
    product = models.ForeignKey(Products, null=True, on_delete=models.PROTECT, related_name='price_list')
    date = models.DateTimeField('Event Date')
    price = models.FloatField(blank=True,)
    price_discount = models.FloatField(blank=False)

trying to get so

Products.objects.prefetch_related('price_list').values('name','price_list__product_id').annotate(price_date=Max('price_list__date'))

only need to add the "price" field

If you want get QuerySet , you can get objects only of one model. But you can easily access values that you need. To get latest related HistoryPrice (by date, not id) you can add a simple function to Products model:

class Products(models.Model):
    ...

    def get_latest_history_price(self):
        return self.price_list.order_by('date').last()    # get object

    def get_latest_history_price_price(self):
        return self.price_list.order_by('date').last().price   # get price

That will help you easily get HistoryPrice object for current Products object, like that:

products = Products.objects.first()           # get an object of Products model
price = products.get_latest_history_price()   # get the newest related HistoryPrice object
price.price                                   # get price field value of HistoryPrice object
price.price_discount                          # get price_discount field value of HistoryPrice object

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