简体   繁体   English

Django:转换queryset的字典

[英]Django: Transform dict of queryset

I use the following code to get my data out of the dict. 我使用以下代码从dict中获取数据。

test = self.events_max_total_gross()
events = organizer.events.all()
    for event in events:
        test.get(event.pk, {}).values()
        [...]

I use this query set to get the data. 我使用此查询集来获取数据。 My question is: Does the transformation at the end makes sense or is there a better way to access the dict (without transforming it first). 我的问题是:最后的转换有意义吗?还是有更好的方法来访问dict(无需先转换)。 As I have several of these my approach doesn't seem to follow the DRY principle. 由于我有几种方法,因此我的方法似乎不遵循DRY原理。

def events_max_total_gross(self):

    events_max_total_gross = (
        Event.objects.filter(
            organizer__in=self.organizers,
            status=EventStatus.LIVE
        )
        .annotate(total_gross=Sum(F('tickets__quantity') * F('tickets__price_gross')))
        .values('pk', 'total_gross')
    )

    """
    Convert this
    [
        {
            'pk': 2,
            'total_gross': 12345
        },
        {
            'pk': 3,
            'total_gross': 54321
        },
        ...
    ]

    to this:
    {
        2: {
            'total_gross': 12345,
        },
        3: {
            'total_gross': 12345,
        }
        ...
    }
    """

    events_max_total_gross_transformed = {}

    for item in events_max_total_gross:
        events_max_total_gross_transformed.setdefault(
            item['pk'], {}
        ).update({'total_gross': item['total_gross']})

    return events_max_total_gross_transformed

Use: 采用:

transformed = { 
    v['pk']: { 'total_gross': v['total_gross'] } for v in events_max_total_gross 
}

This is called a python dict comprehension. 这称为python dict理解。 Google that term if you want tutorials or examples. 如果您需要教程或示例,请用Google的术语。

If I understood it correctly, then for every organiser's event you need total_gross , you can query like this instead of going over events and events_max_total_gross in loop. 如果我对它的理解正确,那么对于每个组织者的事件,您都需要total_gross ,您可以像这样查询,而不是循环查看event和events_max_total_gross。

  1. First get all the events of that particular organizer. 首先获取该特定组织者的所有事件。

    event_ids = Event.objects.filter(organizer=organizer).values_list('id',flat=True)

  2. Run this then: 然后运行:

    Event.objects.filter( id__in=event_ids, organizer__in=self.organizers, status=EventStatus.LIVE ) .annotate(total_gross=Sum(F('tickets__quantity') * F('tickets__price_gross'))) .values('pk', 'total_gross') )

This way you will save your transformation of dict and looping it over again. 这样,您将保存dict的转换并再次将其循环。

In case you need to do like this because of some other requirement then you can use python dict comprehension: 如果由于某些其他要求而需要执行此操作,则可以使用python dict comprehension:

events_max_total_gross_transformed = { event['pk']: { 'total_gross': event['total_gross'] } for event in events_max_total_gross }

But as you have several of these, you might wanna have a look at proxy-models also which might help. 但是,当您拥有其中的几种时,您可能想看看也可能有帮助的代理模型 Here you can write manager functions to help you with your queries. 在这里,您可以编写管理器功能来帮助您进行查询。

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

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