【问题标题】:Get just the values without the fields queryset只获取没有字段查询集的值
【发布时间】:2019-04-25 12:02:30
【问题描述】:

我的views.py中有这个def:

def listar_animais(request, pk):
vacas_no_lote = Animal.objects.filter(id_lote=pk, status=True, sexo=Sexo.F).values('id_animal', 'id_lote', 'id_raca')
return JsonResponse({ 'data' : list( vacas_no_lote )})

我得到了 JSON 格式的返回:

{
  "data": [
    {
      "id_animal": 2,
      "id_brinco": 5456,
      "id_raca": 3
    },
    {
      "id_animal": 4,
      "id_brinco": 5456,
      "id_raca": 3
    },
    {
      "id_animal": 5,
      "id_brinco": 5456,
      "id_raca": 3
    },
    {
      "id_animal": 9,
      "id_brinco": 5456,
      "id_raca": 1
    }
  ]
}

但我只想要这样的值:

{
  'data': [
    ['1', '5471', 'Angus'],
    ['3', '5547', 'Nelore'],
    ['8', '6874', 'Brahman']
  ]
}

我需要这种格式,因为它是 jQuery Datables 的工作方式,如下所述:https://datatables.net/examples/data_sources/ajax

【问题讨论】:

    标签: python json django datatables


    【解决方案1】:

    您可以使用.values_list() 代替.values()

    【讨论】:

    • 有效!但是,有没有办法带来例如“id_raca.description”而不是获取id号?
    • 是的。您可以使用.values_list('id_raca__description')。双下划线访问被引用对象的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2015-09-09
    • 1970-01-01
    • 2019-01-07
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多