Wednesday, October 29, 2014

"Raw query must include the primary key" when inheriting models

Hi,

I have created two models as this:

class Campaign(models.Model):
    name
= models.CharField(max_length=255)

class CampaignExt(Campaign):
    status
= models.IntegerField()


In my APIView I do this:

    def get(self, request, campaign_id, response_format=None):
        campaigns
= CampaignExt.objects.raw("""\
          SELECT
            c.id,
            c.name,
            c.status
          FROM campaign c
          WHERE c.id = %(id)s
        """
% { "id": campaign_id });

The traceback looks like this:
Traceback:
File ".../env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
 
111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File ".../env/lib/python3.4/site-packages/django/views/decorators/csrf.py" in wrapped_view
 
57.         return view_func(*args, **kwargs)
File ".../env/lib/python3.4/site-packages/django/views/generic/base.py" in view
 
69.             return self.dispatch(request, *args, **kwargs)
File ".../env/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
 
403.             response = self.handle_exception(exc)
File ".../env/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
 
400.             response = handler(request, *args, **kwargs)
File ".../campaigns/views.py" in get
 
35.         return Response({'result': serializer.data[0]})
File ".../env/lib/python3.4/site-packages/rest_framework/serializers.py" in data
 
570.                 self._data = [self.to_native(item) for item in obj]
File ".../env/lib/python3.4/site-packages/rest_framework/serializers.py" in <listcomp>
 
570.                 self._data = [self.to_native(item) for item in obj]
File ".../env/lib/python3.4/site-packages/django/db/models/query.py" in __iter__
 
1553.                     raise InvalidQuery('Raw query must include the primary key')

Exception Type: InvalidQuery at /campaigns/4858
Exception Value: Raw query must include the primary key

As I have the primary key in the query I reckon that this should work. But it seems that the CampaignExt model does not know about the primary key as if it has not inherited this from the Campaign model.

When I just create two models with a separated list of fields like this:

class Campaign(models.Model):
    name
= models.CharField(max_length=255)

class CampaignExt(
models.Model):
    name = models.CharField(max_length=255)
    status
= models.IntegerField()

It works as expected. Can you help me what I am missing? Here is my environment:

Django 1.7.1
Python 3.4.2
Rest_Framework 2.4.3

Thanks,
   Tobias.
--
Gruß/Regards,
Tobias Wolff

Senior Architect Workflow Solutions
IPONWEB GmbH

Conrad-Niemann-Straße 28
33442 Herzebrock-Clarholz

Mobil: +49 172 1940702
eMail: twolff@iponweb.net

Geschäftsführer: Thomas Servatius
Amtsgericht: Düsseldorf, HRB 72195

No comments:

Post a Comment