如何在父级序列化器中获得全部子级

时间:2018-08-31 08:34:16

标签: django django-rest-framework django-serializer

我想在父(票证计数器)序列化器中显示与票证计数器关联的工作人员总数。

下面是两个序列化器:

class TicketCounterSerializer(serializers.ModelSerializer):
 workers = WorkerToCounterSerializer(many=True, read_only=True)    
 class Meta:
     model = TicketCounter
     fields = (
               'ticket_counter_name',
               'ticket_counter_description',
               'ticket_counter_address',
               'workers',
               )


class WorkerToCounterSerializer(serializers.ModelSerializer):
 class Meta:
     model = WorkerToTicketCounter
     fields = (
         'user',
         'ticket_counter',
         'worker',
     )

型号:

class TicketCounter(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   ticket_counter_name = models.CharField(max_length=100, default="")
   ticket_counter_description = models.CharField(max_length=1500, default="")
   ticket_counter_address = models.CharField(max_length=1500, default="")


class WorkerToTicketCounter(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   ticket_counter = models.ForeignKey(TicketCounter,related_name="workers")
   worker = models.ForeignKey(User,related_name='worker_for_ticket_counter')

这是我获得结果的方式:

{
        "ticket_counter_name": "First",
        "ticket_counter_description": "firsty",
        "ticket_counter_address": "222fdssssss",
        "workers": [
            {
                "user": 1,
                "ticket_counter": 3,
                "worker": 4,

            },
            {
                "user": 1,
                "ticket_counter": 3,
                "worker": 5,

            },

        ]
 }

这就是我想要的

{
        "ticket_counter_name": "First",
        "ticket_counter_description": "firsty",
        "ticket_counter_address": "222fdssssss",
        "workers": 2 # just the total count
 }

如何只显示总数?

1 个答案:

答案 0 :(得分:2)

您可以使用注释进行此操作,并将其序列化为IntegerField,例如:

class TicketCounterSerializer(serializers.ModelSerializer):
    num_workers = serializers.IntegerField()
    class Meta:
        model = TicketCounter
        fields = (
            'ticket_counter_name',
            'ticket_counter_description',
            'ticket_counter_address',
            'num_workers',
         )

然后在ViewSet中,我们可以指定:

from django.db.models import Count

class TicketCounterViewSet(viewsets.ListApiView):
    queryset = TicketCounter.objects.annotate(num_workers=Count('workers'))
    serializer_class = TicketCounterSerializer

因此,我们用属性TicketCounter注释每个num_workers对象,该属性包含与相关的 WorkerToTicketCounter对象的数量。

但是我个人认为建模有一些奇怪的名称:TicketCounter看起来并不像计数器。尽管我不知道您的应用程序的全部范围,但我认为名为TicketWorker的模型可能更有意义。