Django - 在值列表中添加反向外键

时间:2015-01-05 20:39:20

标签: django

class MyModel(models.Model):
    name = models.SlugField(max_length=50)

class MyRelatedModel(models.Model):
    name = models.SlugField(max_length=50)
    myModel = models.ForeignKey(MyModel)

我想要的是将每个MyModel的相关对象包含在值列表中

myModels = MyModel.objects.all()

data = list(myModels.values('name','MyRelatedModel__name') #off course, this does not work

需要输出(类似):

[{'name': 'MyModel_1', 'myRelatedModel': [{'name': 'myRelatedModel1'}, {'name': 'myReladedModel2'}]}]

有办法吗?也许通过迭代?

2 个答案:

答案 0 :(得分:1)

是的可能:

output = [{'name': mymodel.name, 
           'myRelatedModel': [{'name': related_model.name} for related_model in mymodel.myrelatedmodel_set.all()]} 
          for mymodel in MyModel.objects.all()}]

答案 1 :(得分:1)

实际上,你可以这样:

myModels = MyModel.objects.all()

data = list(myModels.values('name','myrelatedmodel__name'))

更简单的解决方案可能是:

data = MyModel.objects.values('name','myrelatedmodel__name')