【问题标题】:Query django model for data from an external source查询 django 模型以获取来自外部源的数据
【发布时间】:2017-06-16 06:20:36
【问题描述】:

给定一个 django 模型...

models.py

class UserRelationship:
    user_id - IntegerField
    staff_id - IntegerField
    valid_from - DateTimeField

...以及一些从外部 API 检索数据的逻辑。

api.py

class Approval:
    user_id - Int
    created_at - DateTime

带有“批准”列表:

approvals = [{'user_id': <user_id>, 'created_at': <created_at>}, ...]

我需要找到一种在批准“批准”对象列表时派生“staff_id”的有效方法。

我想不出使用 django ORM 的方法。

我知道我们可以使用 Q 对象进行复杂的查找:

from django.db.models import Q

qs = UserRelationship.obejcts.filter(Q(user_id=<user_id>) & Q(created_at__lte=<created_at>))

但这仅适用于user_id/created_at 的单一组合,我如何才能为“批准”的大列表(〜20k +)做到这一点。

任何帮助或提示将不胜感激。非常感谢。

【问题讨论】:

  • 目前你的问题太宽泛了。这些批准从何而来。顺便说一句,你不能发布你的实际模型而不是这些语法不正确的东西吗?

标签: sql django postgresql django-models django-queryset


【解决方案1】:

给定一个“批准”列表(来自外部来源),例如

   approvals = [{'user_id': <user_id>, 'created_at': <created_at>}, ...]

我需要找到一种有效的方法来在批准大约 20k+ 个“批准”对象的列表时找到“staff_id”。

即为每个字典找到一个匹配的行,其中

   approval.user_id = user_relationship.user_id and approval.created_at <= user_relationship.valid_from

根据您的外部数据源、索引等,效率将非常重要。但对于如何制定查询的直接问题,best place to start is with django.db.models.Q

如果您需要执行更复杂的查询(例如,带有 OR 语句的查询),您可以使用 Q 对象。

Q 对象 (django.db.models.Q) 是用于封装关键字参数集合的对象。这些关键字参数在上面的“字段查找”中指定。

filters = Q()
for x in approvals:
    filters |= Q(user_id=x['user_id'], valid_from__lte=x['created_at'])
relationships = UserRelationship.objects.filter(filers)

您可以通过循环访问relationships 查询集来获取staff_id。此示例假定您在批准列表中具有唯一的user_ids,以便您可以返回并将正确的批准与正确的人员 ID 相关联。如果您可以在批准列表中拥有多个相同的user_id,您只需对批准进行分区,使 user_id 在每个分区中不会出现多次。

partitions = []
check_ids = []
for x in approvals:
    current_partition = None
    current_check_id = None
    for partition, check_id in zip(partitions, check_ids):
        if x['user_id'] not in check_id:
            current_partition = partition
            current_check_id = check_id

    if current_partition is None:
        partitions.append(list())
        check_ids.append(set())
        current_partition = partitions[-1]
        current_check_id = check_ids[-1]
    current_check_id.add(x['user_id']
    current_partition.append(x)

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2013-11-29
    • 2019-04-17
    • 2018-02-07
    • 2018-02-09
    相关资源
    最近更新 更多