求 django 如何实现多个model返回的queryset转成 list 格式

我在view中调用model,我的两个model是一对多的关系,我希望能把A和B表中的记录查出来转成list格式,再遍历A的list,然后将B与之匹配的记录拼接起来

阅读 10.7k
2 个回答

perhaps you can use select with related and then convert the results to list

简化的

def A(Model):
    title=field()
    other1=field()
    other2=field()
   
def B(Model):
    a=field(A)
    b=field()
    c=field()

query_list = B.object.value_list('b','c','a__title','a__other1','a__other2')

query_list就是一个list,返回的结果是元组(id,b,c,a__title,a__other1,a__other2),
也可以用values代替value_list返回的是[{'id':1,'b':'11'..},{'id':2,'b':'22'..}]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题