简体   繁体   English

在Python Dict中循环的单行嵌套

[英]Single line nesting for loops in a Python Dict

I have two models: Sites and Regions. 我有两个模型:站点和区域。 A Region has many Sites. 区域有许多站点。

class Site(models.Model):

  name = models.CharField(max_length=200, unique=True)

class Region(models.Model):

  name = models.CharField(max_length=200, unique=True)
  sites = models.ManyToManyField('Site')

i would like to loop through the queryset so as to get a dict (which will eventually become JSON) that looks like this: 我想遍历查询集,以获得一个如下所示的dict(最终将成为JSON):

regions = [
    {
        id: 1,
        name: "Region 1",
        sites: [
            {
                id: 1,
                name: "Site 1"
            },
            {
                id: 2,
                name: "Site 2"
            }
        ]
    },{
        id: 2,
        name: "Region 2",
        sites: [
            {
                id: 3,
                name: "Site 3"
            },
            {
                id: 4,
                name: "Site 4"
            }
        ]
    },
]

The thing is, I would like to do it in one line. 问题是,我想在一行中做到这一点。 I feel like I'm on the right track with {Region.name : {int(Site.id) : Site.name for Site in Region.sites.all()} for Region in Region.objects.all()} but I'm having trouble nesting the loops. 我觉得我{Region.name : {int(Site.id) : Site.name for Site in Region.sites.all()} for Region in Region.objects.all()}的正确轨道我在嵌套循环时遇到了麻烦。 I feel like it should be something like the below, but this is not working: 我觉得它应该像下面这样,但这不起作用:

{ 'id' : Region.id, 'name': Region.name, 'children' : { 'id': int(Site.id), 'name' : Site.name} for Site in Site.objects.all()} for Region in Region.objects.all()}

I didn't test it, but maybe you want something like: 我没有测试它,但也许你想要的东西:

regions = [dict(r.items() + [('sites', r.site_set.all().values('id', 'name'))]) for r in Record.objects.all().values('id', 'name')]

UPD. UPD。 But as Brandon noted, it would be better to not use such complicated oneliners. 但正如布兰登指出的那样,最好不要使用这种复杂的oneliner。

尝试这个:

{'id' : region.id, 'name': region.name, 'sites' : { 'id': int(site.id), 'name' : site.name for site in region.sites.objects.all()} for region in Region.objects.all()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM