简体   繁体   中英

calculated property in Django model with QuerySet

I am working on a frontend that consumes a Django backend. I want to add a new calculated property to one Django model, that contains chart-data for amCharts.

After some research i found out, that using @property would be the way to go here.

However all the viewsets implemented atm use querysets, which as i found out after some googling ignore calculated properties.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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