注释一个额外的字段,但在 django rest 中的 api 响应中只显示一次
annotate an extra field but show just once in api response in django rest
我必须在 get api 中使用 annotate 添加一个额外的字段。该字段类似于所有对象的字段计数,而不是特定对象。我希望它在 get api 的响应中只出现一次。如果我使用注释,它会出现在所有对象响应中。如何实现??
我的模特:
class Package(models.Model):
location = models.CharField()
bought_times = models.IntegerField(default=0)
/....................../
现在,如果我使用这样的注释:
qs = Package.objects.filter(....).annotate(whole_bought_counts=Sum("bought_times") or some logic)
在响应中它会像这样:
{
id = 1,
localtion = Paris,
bought_times = 22,
whole_bought_counts =72,
}
{
id = 1,
localtion = Miami,
bought_times = 16,
whole_bought_counts =72,
}
id = 1,
localtion = Switzerland,
bought_times = 24,
whole_bought_counts =72,
}
我需要 whole_bought_counts 只出现一次,因为该计数仅用于仪表板信息。出现几次会使它出现 100 多次,这使得 api 相当慢。不是吗??
可以将其他数据添加到视图集的响应中。例如
class PackageViewSet(ModelViewSet):
model = Package
serializer_class = PackageSerialzer
queryset = Package.objects.all()
def get_queryset(self):
qs = Package.objects.filter(...) # Whatever you want your qs to be
return qs
def list(self, request):
queryset = self.get_queryset()
serializer = self.serializer_class(queryset, many=True)
addional_data = {
'my_data': ... # Any data, from your queryset or else
}
return Response([addional_data, serializer.data])
我必须在 get api 中使用 annotate 添加一个额外的字段。该字段类似于所有对象的字段计数,而不是特定对象。我希望它在 get api 的响应中只出现一次。如果我使用注释,它会出现在所有对象响应中。如何实现??
我的模特:
class Package(models.Model):
location = models.CharField()
bought_times = models.IntegerField(default=0)
/....................../
现在,如果我使用这样的注释:
qs = Package.objects.filter(....).annotate(whole_bought_counts=Sum("bought_times") or some logic)
在响应中它会像这样:
{
id = 1,
localtion = Paris,
bought_times = 22,
whole_bought_counts =72,
}
{
id = 1,
localtion = Miami,
bought_times = 16,
whole_bought_counts =72,
}
id = 1,
localtion = Switzerland,
bought_times = 24,
whole_bought_counts =72,
}
我需要 whole_bought_counts 只出现一次,因为该计数仅用于仪表板信息。出现几次会使它出现 100 多次,这使得 api 相当慢。不是吗??
可以将其他数据添加到视图集的响应中。例如
class PackageViewSet(ModelViewSet):
model = Package
serializer_class = PackageSerialzer
queryset = Package.objects.all()
def get_queryset(self):
qs = Package.objects.filter(...) # Whatever you want your qs to be
return qs
def list(self, request):
queryset = self.get_queryset()
serializer = self.serializer_class(queryset, many=True)
addional_data = {
'my_data': ... # Any data, from your queryset or else
}
return Response([addional_data, serializer.data])