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

Django - Add reverse foreign key in values list

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'}]}]

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

是的,有可能:

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

实际上,你可以这样得到:

myModels = MyModel.objects.all()

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

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

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