【问题标题】:How can I convert django model object and related object in to list of dictionary?如何将 django 模型对象和相关对象转换为字典列表?
【发布时间】:2016-02-13 23:57:08
【问题描述】:

模型会是这样的

class Customer(models.Model):
    name = models.CharField(max_length=100)

class Payment(models.Model):
    amount = models.DecimalField(max_digits=4, decimal_places=2) 
    customer = models.ForeignKey(Customer, models.CASCADE)

我想列一个类似

的列表
[
    {
        'name': 'Tom',
        'Payment': [{'amount': 10},{'amount': 20}]
    },
    {
        'name': 'Jack',
        'Payment': [{'amount': 30},{'amount': 10}]
    }
]

我尝试使用值,但它要求我知道相关对象的所有字段名称是否有其他方法可以在不知道字段名称的情况下执行此操作?

【问题讨论】:

  • 好吧,在你的例子中(至少某些)名字扮演着特殊的角色。例如。属性customer 没有打印出来,payment 是类名的小写...所以你想如何概括这种情况并不简单。
  • 我的错误付款的 P 应该是大写的。我希望转换器忽略外键字段,因为有关外键的信息已存储在列表中(客户)
  • 你想在哪里使用这个列表?如果在某些 API 中,您应该使用一些 REST 框架(即 Django Rest Framework)并使用serializers 将您的模型集(QuerySet)转换为序列化结构。

标签: python django dictionary django-models


【解决方案1】:
q_customer = Customer.objects.all()
L = []
for customer in q_custmer:
  Dcustomer = {'name':customer.name,
         'Payment':[{'amount',x.amount} for x in customer.payment_set]
  L.append[D]

# L now holds the list

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 2015-06-08
    • 2018-07-15
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多