Issue
views.py
def inventory_display(request):
if request.user.vendor == True and request.user.vendor_approval == True:
vendor = CustomUser.objects.get(id=request.user.id)
vendor_product = vendor.vendor_user.all()
items = vendor_product[0].product_variants.all()
return render(request, 'vendor/inventory_display.html',{'vendor_product':vendor_product, 'items':items})
Html
{% for product in vendor_product %}
{% for item in items %}
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{product.created|date:"d-m-y"}}</td>
<td>{{product.edited|date:"d-m-y"}}</td>
<td>{{product.vendoruser}}</td>
<td><a href="{% url 'loomerang_admin:product_details' %}">{{product.product_id}}</a></td>
<td>{{item.item_num}}</td>
<td>{{item.variant_value}}</td>
<td>{{item.initial_stock}}</td>
<td>2</td>
<td>{{item.approval_status}}</td>
<td>{{item.approved_date|date:"d-m-y"}}</td>
<td>{{product.approved_by}}</td>
</tr>
{% endfor %}
{% endfor %}
I am fetching data from 3 different models. I do fetch all the data from these models every time. What if I want to get the newest row only whenever the new row is added? I have included the User, Product, Productvariants models in the question. I am showing data in the template by for loop. Without forloop i am getting repeated data in template, I want the latest data that will not exist in the template.
Solution
add this field in your model
created_at = models.DateTimeField(auto_now_add=True)
it will automatically add timestamp whenever object is created. and when you are geting objects use this query
ModelName.objects.all().order_by('-created_at')
Answered By - Abdul Raffay
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.