Home > Mobile >  how to fetch only the newest rows from the model in django and show it as a table?
how to fetch only the newest rows from the model in django and show it as a table?

Time:12-31

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 %}

models.py

class CustomUser(AbstractUser):
  username = None
  email = models.EmailField(_('email address'), unique=True)
  mobile_number = models.PositiveBigIntegerField(blank=False, null=True)
  first_name = models.CharField(max_length=200)
  last_name = models.CharField(max_length=200)
  USERNAME_FIELD = 'email'
  REQUIRED_FIELDS = []
  userid = models.CharField(max_length=100, unique=False, null=True)
  approved_by = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
  approved_date = models.DateField(null=True, blank=True)
  status = models.CharField(max_length=10,choices=STATUS_CHOICES,default="Waiting")
  objects = UserManager()

def __str__(self):
    return str(self.userid)   ' '   str(self.first_name)




class Product(DateTimeModel):
  maincategory = models.ForeignKey(MainCategory, null=True, related_name='main_category', on_delete=models.CASCADE)
  productcategory = models.ForeignKey(ProductCategory, null=True, related_name='product_category',
                                    on_delete=models.CASCADE)
  subcategory = models.ForeignKey(SubCategory, null=True, related_name='sub_category', on_delete=models.CASCADE)
  product_id = models.CharField(max_length=200)
  vendoruser = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, related_name='vendor_user')
  product_name = models.CharField(max_length=200)
  brand_name = models.CharField(max_length=200)
  others_attribute = models.CharField(max_length=500, null=True, blank=True)
  attribute_values = models.JSONField()
  is_approved = models.BooleanField(default=False)
  thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)  # Change uploads to thumbnails
  
def __str__(self):
    return self.product_name

 class ProductVariants(DateTimeModel):
   item_num = models.CharField(max_length=100, null=True, blank=True)
   product_id = models.ForeignKey(Product, related_name="product_variants", null=True, on_delete=models.CASCADE)
   variant_type = models.ForeignKey(VariantsType, related_name="product_variants", null=True, on_delete=models.CASCADE)
   variant_value = models.ForeignKey(VariantsValue, related_name="product_variants", null=True,
                                  on_delete=models.CASCADE)
   price = models.PositiveIntegerField(null=True)
   initial_stock = models.PositiveIntegerField(null=True)
   weight_of_product = models.PositiveIntegerField(null=True)

def __str__(self):
    return str(self.id)

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.

CodePudding user response:

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')

CodePudding user response:

Try adding the index number in your views:

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()[0] 
         items = vendor_product[0].product_variants.all()[0]
         return render(request, 'vendor/inventory_display.html',{'vendor_product':vendor_product, 'items':items})

And remove the for loop from the template:

                <tr>
                  <th scope="row">1</th>
                  <td>{{vendor_product.created|date:"d-m-y"}}</td>
                  <td>{{vendor_product.edited|date:"d-m-y"}}</td>
                  <td>{{vendor_product.vendoruser}}</td>
                  <td><a href="{% url 'loomerang_admin:product_details' %}">{{product.product_id}}</a></td>
                  <td>{{items.item_num}}</td>
                  <td>{{items.variant_value}}</td>                       
                  <td>{{items.initial_stock}}</td>
                  <td>2</td>
                  <td>{{items.approval_status}}</td>
                  <td>{{items.approved_date|date:"d-m-y"}}</td>
                  <td>{{vendor_product.approved_by}}</td>
                </tr>
             

CodePudding user response:

You can get the latest inserted item in multiple ways

last() method

vendor = CustomUser.objects.last()

order_by() method

vendor = CustomUser.objects.order_by('-id').first()

latest() method

vendor = CustomUser.objects.latest('id')
  • Related