Search code examples
pythondjangoamcharts

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'])

Solution

  • As suggested by @dirkgroten i used the SerializerMethodField to add the new json-field before django ships my result.