BeJay
BeJay

Reputation: 425

Django: API with accumulated data

I am new to python and want to implement an API with accumulated data. I've seen a lot of information about the possibility to browse the database with the django rest framework but I cannot find the right solution to view data which is analyzed or summarized.

For example, I have data about some newspaperarticles:

articles: [
  {
    name: "test 1",
    views: 10000
  },
  {
    name: "test 2",
    views: 20000
  },
  {
    name: "test 3",
    views: 30000
  }
] 

I want to show analyzed data like

summary: {
  name: "articles",
  sum_views: 60000,
  article_count: 3
}

What would be the best practice if I want to use django and the django rest framework?

Upvotes: 0

Views: 79

Answers (3)

BeJay
BeJay

Reputation: 425

I solved the problem with SQL. I've created accumulating MySQL-View which can be seen in the usual Django way. Because after the MySQL-View was created, you can just write a model in Django and create a Django-view.

To make the MySQL Views independent of the system I've written a MySQL creation script in a class named 'db_views.py' which were instantiated in the apps.py file

class ArticlesConfig(AppConfig):
    """Standard config module"""
    name = 'articles'

    def ready(self):
        """Config method if application is ready"""
        post_migrate.connect(create_view, sender=self)

Upvotes: 0

Himanshu Patel
Himanshu Patel

Reputation: 640

Place it inside views.py and override get_queryset method.

class MyViewSet(viewsets.ModelViewSet):

    queryset = MyModel.objects.all()
    serializer_class = MySerializer

    def get_queryset(self):
        # filter your query set here and return a queryset (not an object)
        return queryset

This has to be a comment of @Tom Wojcik but I don't have enough reputation to comment.

Upvotes: 1

Valery Ramusik
Valery Ramusik

Reputation: 1573

If articles resource rout is "/article/" then summary may be "/article/summary/"

Upvotes: 0

Related Questions