简体   繁体   English

使用 QuerySet 计算 Django model 中的属性

[英]calculated property in Django model with QuerySet

I am working on a frontend that consumes a Django backend.我正在开发一个使用 Django 后端的前端。 I want to add a new calculated property to one Django model, that contains chart-data for amCharts.我想向一个包含 amCharts 图表数据的 Django model 添加一个新的计算属性。

After some research i found out, that using @property would be the way to go here.经过一些研究,我发现使用@property将是 go 的方法。

However all the viewsets implemented atm use querysets, which as i found out after some googling ignore calculated properties.然而,所有实现 atm 的视图集都使用查询集,正如我在一些谷歌搜索后发现的,忽略了计算的属性。

  1. Is there a way to keep the queryset and let it use my calculated property?有没有办法保留查询集并让它使用我的计算属性?
  2. If not: Would manually writing out all the queryset operations solve the problem?如果不是:手动写出所有查询集操作会解决问题吗?

Code:代码:

# models.py
class MyModel:
    # Normal props

    @property
    def calced(self):
        return somecalc

# views.py
class MyModelView(ModelViewSet):
    serializer_class = MyModelSerializer

    def get_queryset(self):
        return MyModel.objects.filter(id=self.kwargs['id_pk'])

As suggested by @dirkgroten i used the SerializerMethodField to add the new json-field before django ships my result.正如@dirkgroten 所建议的,我在 django 发送我的结果之前使用了SerializerMethodField添加新的 json 字段。

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

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