Guilherme GM
Guilherme GM

Reputation: 577

django - Filter foreign key in a queryset

In the following model:

class Product(models.Model):
    name = models.CharField(max_length = 255)
    created_in = models.DateTimeField(auto_now=True)

class Price(models.Model):
    product = models.ForeignKey(Product)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    created_in = models.DateTimeField(auto_now=True)

I want to do things like this:

products = Product.objects.filter(price__gte=Decimal(10)) #It considered all prices I just need the last one

How do i query a product considering only the last price "created_in" related?

Thanks!!

Upvotes: 1

Views: 1440

Answers (1)

alecxe
alecxe

Reputation: 474271

latest() is what you need:

Returns the latest object in the table, by date, using the field_name provided as the date field.

products = Product.objects.filter(price__gte=Decimal(10)).latest('price__created_in')

Upvotes: 1

Related Questions