简体   繁体   English

如何在相同模型的 django 序列化程序中“分组”

[英]How to "group by" in django serializers for same model

I am new to Django-Python and learning to build serializers.我是 Django-Python 的新手,正在学习构建序列化程序。 I understand the basic implementation of Serializers but stuck with this following particular requirement.我了解序列化程序的基本实现,但坚持以下特定要求。

This is my Customer Events model -这是我的客户事件模型 -

class CustomerEvents(models.Model):
       account_number = models.BigIntegerField(blank=False)
       event_type = models.CharField(max_length=255, blank=False, null=False)

Sample records in CustomerEvents: CustomerEvents 中的示例记录:

Account Number    Event Type
A12345             Billing Issues
A12345             Video Services
A12345             Sales

I want to create a CustomerEventsSerializer which will return values as below:我想创建一个 CustomerEventsSerializer 它将返回如下值:

{ 
  "account_number" : A12345, 
  "event_types"    : ['Billing Issues', 'Video Services', 'Sales']
}

You can create a dummy serializer for it.您可以为它创建一个虚拟序列化程序。

CustomerEventsSerializer(serializers.ModelSerializer):  
    def to_representation:(self,obj):  
        rep= super(CustomerEventsSerializer,self).to_representation(obj)  
        rep['events']= [ customer.event for customer in CustomerEvents.objects.filter(account_number=obj.account_number)]  
        return rep  
    class Meta:  
        model = CustomerEvents  
        fields = ('account_number',)

You can use this module https://github.com/kako-nawao/django-group-by which allows you to group by and return queryset.您可以使用此模块https://github.com/kako-nawao/django-group-by ,它允许您分组并返回查询集。

from django.contrib.postgres.aggregates.general import ArrayAgg

qs = CustomerEvents.objects.group_by('account_number').annotate(
        event_types=ArrayAgg('event_type')))

Now you can create CustomerEventsSerializer with account_number and event_types method to handle the list for qs[0].event_types .现在您可以使用account_numberevent_types方法创建CustomerEventsSerializer来处理qs[0].event_types的列表。

class CustomerEventsSerializer(serializers.ModelSerializer):
    event_types = serializers.ListField()

    class Meta:
        model = CustomerEvents
        fields = ('account_numer', 'event_types')

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

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