How to use raw query in django tastypie and join tables?

43 views Asked by At

I am trying to use a raw query in django tastypie queryset. But django is throwing me the following exception:

<error_message>'RawQuerySet' object has no attribute 'filter'</error_message>

I also tried using ModelName.objects.filter() to join different tables. It's not working either. Django throwing the following exception: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

My tastypie models.py file looks like this:

import datetime

from django.db import models
from tastypie.resources import ModelResource
from logsheet.models import *
from generation.models import *
from django.contrib.auth.models import User
from tastypie.authentication import BasicAuthentication
from django.db.models import Sum


class EnergyPlantWiseResource(ModelResource):
    class Meta:
        present_time = datetime.datetime.today()
        previous_month = present_time.month - 1
        present_year = present_time.year
        queryset = EnergyPlantWise.objects.raw('SELECT 1 id, SUM(ep.kwh), f.name FROM energy_plant_wise ep, fuel f WHERE ep.fuel_id=f.id AND MONTH(ep.date)=%s AND YEAR(ep.date)=%s GROUP BY f.name',[previous_month, present_year])
        # queryset = EnergyPlantWise.objects.all()
        resource_name = 'epw'
        allowed_methods = ['get']
        excludes = ['id']
1

There are 1 answers

1
Gabriel Okemwa On

The error you're encountering, <<RawQuerySet' object has no attribute 'filter',>> is because a RawQuerySet does not support the typical filtering operations that a regular Django queryset does.

 RawQuerySet is used when you need to execute raw SQL queries directly and retrieve the results as model instances. Do this instead:
class Meta:
        resource_name = 'epw'
        allowed_methods = ['get']

    def get_object_list(self, request):
        present_time = datetime.datetime.today()
        previous_month = present_time.month - 1
        present_year = present_time.year

        cursor = connection.cursor()
        cursor.execute(
            'SELECT SUM(ep.kwh), f.name FROM energy_plant_wise ep INNER JOIN fuel f ON ep.fuel_id=f.id WHERE MONTH(ep.date)=%s AND YEAR(ep.date)=%s GROUP BY f.name',
            [previous_month, present_year]
        )

        results = []
        for row in cursor.fetchall():
            # Create a dictionary to hold the result
            result_dict = {
                'kwh_sum': row[0],
                'fuel_name': row[1],
            }
            results.append(result_dict)

        return results