Home > Back-end >  Django: Getting last value by date from related model in html
Django: Getting last value by date from related model in html

Time:07-16

I Just had a question:

So on my parent product overview I show the name of the product and it's URL but there is also a related model to that parent model which holds the history of the prices over time.

What I want to do is show also the latest price in my table here is my code:

models.py:

class Product(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, default=None, null=True, blank=True)
    url = models.CharField(max_length=255, default=None, null=True, blank=True)
    creation_date = models.DateTimeField(auto_now_add = True)
    update_date = models.DateTimeField(auto_now = True)


class PriceHistory(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    product_info  = models.ForeignKey(Product, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=20, decimal_places=2)    
    creation_date = models.DateTimeField(auto_now_add = True)

My views.py

@login_required
def overview(request):
    all_products = Products.objects.filter(user=request.user)
    general_context = {'all_products': all_products}
    return render(request, 'overview.html', general_context)    

and my html

    <h4>Overview Products</h4>
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>Name</th>
              <th>Url</th>
              <th>Last price</th>
            </tr>
          </thead>
          <tbody>
            {% for product in all_products %}   
                <tr>                    
                <td>{{ forloop.counter }}</td>
                <td>{{ product.name }}</td>
                <td>{{ product.url }}</td>
                <td>{{ product.id.price}}</td>
                <td></td>
                {% endfor %}
              </tr>
          </tbody>
        </table>


How to get the latest price also together with my product in my html overview?

I tried with {{ product.id.price}}. I think I'm not far off but can't get my head around it.

CodePudding user response:

You can get the most recent price history using the reverse accessor, ordering by the creation date and then selecting the first object in the queryset:

latest_price_history = product.pricehistory_set.order_by('-creation_date').first()

As to how you get this into your template, you could add this as a model method like so:

class Product(models.Model):
   ...

   @property
   def latest_price(self):
      return self.pricehistory_set.order_by('-creation_date').first().price

Then in your template you can call it by:

{{ product.latest_price }}
  • Related