gpt4 book ai didi

django - 如何在父序列化程序中获取总子项

转载 作者:行者123 更新时间:2023-12-02 00:58:46 24 4
gpt4 key购买 nike

我想在父(票务柜台)序列化程序中显示与票务柜台关联的 worker 总数。

下面是两个序列化器:

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
}

如何只显示总数?

最佳答案

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

class TicketCounterSerializer(serializers.ModelSerializer):
num_workers = <b>serializers.IntegerField()</b>
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):
<b>queryset = TicketCounter.objects.annotate(num_workers=Count('workers'))</b>
serializer_class = TicketCounterSerializer

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

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

关于django - 如何在父序列化程序中获取总子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52111521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com