获取字典列表中项的反向关系

2024-10-02 18:26:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典列表(“DailyEnrollment”对象的查询集),如下所示:

[
{'location_id': 1, 'student_count': 780}, 
{'location_id': 4, 'student_count': 535}, 
{'location_id': 6, 'student_count': 496}
]

有一个Location对象,它有一个属性name——这个列表中的location_id与一个Location对象相关,但它不是一个外键(在模型中),这是因为在我们的项目中其他应用程序是如何与之交互的。你知道吗

有没有一种简单的方法可以遍历这个列表,为location_id获取每个字典location.name,并将其作为location_name附加到字典中?你知道吗

我正在考虑一个列表理解里面的字典理解-但我不知道这是多么的python。你知道吗

型号:

class Location(models.Model):
    name = models.CharField(max_length=50)
    short_name = models.CharField(max_length=50)

DailyEnrollment是从用外部数据构建的视图中获取的数据

class DailyEnrollment(SchoolModel):
    id            = models.IntegerField(db_column='ID', primary_key=True)
    location_id   = models.IntegerField(db_column='schoolID')
    grade         = models.CharField(db_column='grade', max_length=10)
    end_year      = models.IntegerField(db_column='endYear')
    run_date      = models.DateField(db_column='runDate')
    student_count = models.IntegerField(db_column='studentCount')

在我看来,这就是我如何得到我的每日报名

# get past enrollments
    past_daily_enrollments = DailyEnrollment.objects.filter(
                run_date=datetime.strptime(since_date, '%m-%d-%Y'),
                location_id__lte='31',
                end_year='2018')

我创建了一个“新列表”,其中所有数据都分组在location_id上,总数为student_count

location_data = past_daily_enrollments.values('location_id').annotate(
    student_count=Sum('student_count')
)

这就是我问的问题。我有“location\u data”,这是我的字典列表。你知道吗


Tags: 对象nameid列表db字典modelscount
2条回答

你的模型不对。我怀疑它们是通过对现有数据库运行inspectdb生成的;这样做的一个问题是它有时无法检测外键。但是,在您的例子中,location_id显然是Location的外键,因此您应该这样声明它:

location = models.ForeignKey('Location', db_column='schoolID')

完成此操作后,只需通过值调用中的双下划线语法遵循关系:

past_daily_enrollments.values('location__name')...

所以(暂时)我开始通过几个步骤手动协调它们。你知道吗

首先,我使用我的位置数据,得到一个所有ID的列表,如下所示:

location_ids   = [s['location_id'] for s in location_data]

然后我得到这些ID的位置对象:

location_items = Location.objects.filter(
        id__in=location_ids
    )

然后我做了一个小字典,上面有ID和名字:

location_names = [
        {'location_id':s.id, 'location_name': s.name}
        for s in location_items
    ]

然后,我将两个字典列表链接在一起,并根据将每个字典绑定在一起的“location\u id”从中创建一个新的字典列表。你知道吗

additional_location_data  = defaultdict(dict)
for d in chain(past_enrollments, location_names):
    additional_location_data[d['location_id']].update(d)

这有助于协调location\u id与location对象的名称,并将名称放入字典(列表内部)中的适当位置。你知道吗

这可能是相当'丑陋'目前-但我会担心清理它以后。你知道吗

相关问题 更多 >