【问题标题】:Django Model Filter: need to return the name not the id of a foreign keyDjango 模型过滤器:需要返回名称而不是外键的 id
【发布时间】:2020-07-06 04:14:44
【问题描述】:

我正在尝试在名为 WorkPacket 的模型中过滤一些数据

work_packets_01012017_25032020 = WorkPacket.objects.all()

work_packets_01012017_25032020 = 
work_packets_01012017_25032020.filter(start_date__gte=datetime.date(2017, 1, 1), 
start_date__lte=datetime.date(2020, 03, 25)).values('id', 'number', 'name', 'description', 
'value', 'type', 'status', 'daily_rate', 'creator', 'creation_date', 'closer', 
'closure_date', 'start_date', 'estimated_closure_date', 'estimated_days_overrun', 
'invoice_coding', 'issued_pos', 'purchase_order', 'number_of_days', 
'number_of_billed_days','number_of_remaining_days', 'number_of_over_run_days', 
'effective_daily_rate', 'ahead_behind', 'earnings', 'remaining_earnings', 'reported', 
'projects', 'purchase_order__customer', 'purchase_order__owner')

此表有一个与另一个模型相关的外键“purchase_order”。在返回值的末尾,我试图附加“purchase_order__customer”、“purchase_order__owner”。这有效,但返回的是客户和所有者的 ID,而不是名称。我怎样才能返回名称呢?

谢谢

【问题讨论】:

    标签: python django model foreign-keys


    【解决方案1】:

    如果要返回相关模型的特定字段,可以使用如下:

    .values(..., 'purchase_order__customer__name', 'purchase_order__owner__name')
    

    【讨论】:

      猜你喜欢
      • 2018-03-19
      • 2020-08-19
      • 1970-01-01
      • 2015-05-08
      • 2020-12-22
      • 2016-07-03
      • 2019-06-26
      • 2018-02-03
      • 1970-01-01
      相关资源
      最近更新 更多