Skip to content
Advertisement

Python Django Rest – Return extra field with lowest, highest and average values of some other field

I’m new to Django and APIs in general and I want to create a Django based API using Django Rest Framework.

Here’s what I want to do:

Endpoint to age range report:

JavaScript

Response:

JavaScript

Endpoint to salary range report:

JavaScript

Response:

JavaScript

I have two apps, employees and reports.

Here’s employees/models.py:

JavaScript

Here’s employees/serializers.py:

JavaScript

I’m not sure how to create my views and serializers for my report app. How should I approach this?

How can I return an extra field with a calculation between values of another field? Should I create a custom field in my serializer?

By reading the docs I’ve figured that the query I should use should be something like:

JavaScript

Or maybe, for salary for example:

JavaScript

But how would I go about using it?

I don’t know where to use or how to go about it as my understanding of APIs and Django Rest Framework is still very lacking.

Should it go in my reports/view.py? Or in my employees/serializers.py?

Should I create a reports/serializers.py file?

Do I need a reports/model class with lowest, highest, average fields plus an employee object field?

Should I override the list() function of my ReportSalaryListAPIView class in my reports/views.py? (This class doesn’t exist yet)

I’m very lost and confused. Please help point me in the right direction.

Thank you in advance.


Edit:

My employees/model.py now looks like this:

JavaScript

My employees/serializers.py now:

JavaScript

I’ve run the makemigrations and migrate commands with manager.py, just in case.

But I’m now running into this error when trying to create a new employee:

JavaScript

What is happening?

Advertisement

Answer

Idea

No extra fields are needed to store the calculated values since they are calculated based on the rows in the database.

  1. First you find min_salary, max_salary, and avg_salary by using the aggregate method.
  2. Use found min_salary and max_salary to find employees.
  3. Implement a serializer class that serializes highest, lowest, and average employee salary report.
  4. Serialize the lowest, highest, and avarage by using the implemented serializer class.

Code

In my opinion, the code for performing the logic should be on another layer, usually called the service layer.

JavaScript
JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement