简体   繁体   English

如何在 django 查询集中获取名称而不是 id

[英]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我需要获取 customer_name 但它返回 id 并请告知如何将我的查询集更新为相关值

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这是 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它在 html 中返回 id 而不是客户名称

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

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:我想我找到了答案,不仅我需要在我的视图中添加'customer_name__username'而不是'customer_name',而且还需要在我的 html 中添加“__username”以及我在 html 中的标签应该是这样的:

{{ order.customer_name__username }} {{ order.customer_name__username }}

This is for Django file: __ .这适用于 Django 文件: __ Django template use . Django 模板使用. to represent ForeignKey relation fields.表示ForeignKey关系字段。

Correct answer might be:正确答案可能是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM