Michael Harvey
Michael Harvey

Reputation: 63

How to get name instead of id in django queryset

I need to get customer_name but it returns id and please advise how to update my queryset to the related value

class Orders(models.Model):
    customer_name = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    qty = models.IntegerField()
    date = models.DateField(auto_now_add=timezone.now)

    def __str__(self):
        return "{}".format(self.customer_name)


    def get_absolute_url(self):
        return reverse('customer-orders', kwargs={'customer_name': self.customer_name})

and this is the view.py

class OrdersListTotal(SuperuserRequiredMixin, ListView):
    
    model = Orders, User
    template_name = 'orders/orders_list_total.html' #<to change the template name to a existing one> 
    context_object_name = 'orders'
    paginate_by = 10
    


    def get_queryset(self):
        orders = Orders.objects.values('customer_name', 'product').annotate(qty=Sum('qty'))
        return orders

and it returns id instead of customer name in html

<table id="order-table" class="order-table">
  <thead>
    <tr>
      <th></th>
      <th>Customer Name</th>
      <th>Product</th>
      <th>Qty</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td><a class="mr-2">{{ order.customer_name }}</a></td>
      <td><a class="mr-2">{{ order.product }}</a></td>
      <td>{{ order.qty}}</td>
    </tr>
  </tbody>

Upvotes: 1

Views: 1619

Answers (2)

Michael Harvey
Michael Harvey

Reputation: 63

I think I found the answer not only I needed to add 'customer_name__username' in my view instead of 'customer_name' but also need to add "__username" in my html as well my tag in html should be like this:

<a class="mr-2">{{ order.customer_name__username }}</a>

Upvotes: 1

Siva Sankar
Siva Sankar

Reputation: 1820

This is for Django file: __. Django template use . to represent ForeignKey relation fields.

Correct answer might be:

<td><a class="mr-2">{{ order.customer_name.username }}</a></td>

Upvotes: 0

Related Questions