【问题标题】:How to get name instead of id in django queryset如何在 django 查询集中获取名称而不是 id
【发布时间】:2021-08-29 11:25:41
【问题描述】:

我需要获取 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})

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

它返回 id 而不是 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>

【问题讨论】:

    标签: python django django-models orm django-queryset


    【解决方案1】:

    这是 Django 文件:__。 Django 模板使用. 表示ForeignKey 关系字段。

    正确答案可能是:

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

    【讨论】:

      【解决方案2】:

      我想我找到了答案,不仅我需要在我的视图中添加“customer_name__username”而不是“customer_name”,而且还需要在我的 html 中添加“__username” 我在 html 中的标签应该是这样的:

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

      【讨论】:

        猜你喜欢
        • 2020-11-12
        • 1970-01-01
        • 1970-01-01
        • 2018-01-16
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        • 2021-09-10
        相关资源
        最近更新 更多