Reputation: 2009
in accordance with https://docs.djangoproject.com/en/1.10/topics/db/sql/
I have
query = "SELECT * FROM model_name"
objs = []
for obj in models.ModelName.objects.raw(query):
objs.append(obj)
yet it complains Raw query must include the primary key error
why is this happening
ModelName code:
class ModelName(ModelBase):
fielda = models.CharField(max_length=255)
class ModelBase(models.Model):
id = models.IntegerField(primary_key=True)
Upvotes: 1
Views: 3179
Reputation: 524
According to your question it is likely that you have something wrong in the table name. Django table convention is as follows:
appname_modelname
so say you have polls apps and Poll model class inside of it polls/models.py
class Poll(models.Model):
title = models....
then your table name in sql will be polls_poll.
it'll be better if you explicitly import the models first in order to avoid confusions.
from polls.models import Poll
query = "SELECT * FROM polls_poll"
objs = []
for obj in Poll.objects.raw(query):
objs.append(obj)
so in your case the query should be
select * from MyApp_ModelName;
and I think for the primary key problem, if you are not intended to use something like CharField "prod001" then AutoField is a way to go.
otherwise in your case of your model try this solution inside models.py . Just to make sure that your primary_key is unique.
from django.db.models.signals import pre_save
def add_id(instance, new_id=None):
id = instance.id
if new_id is not None:
id = new_id
checker = ModelName.objects.filter(id=instance.id).order_by("-id")
exists = checker.exists()
if exists:
new_id = len(ModelName.objects.all()) + 1
return add_id(instance, new_id=new_id)
return id
def pre_save_post_receiver(sender, instance, *args, **kwargs):
instance.id = add_id(instance)
pre_save.connect(pre_save_post_receiver, sender=ModelName)
Upvotes: 0
Reputation: 183
Are you sure you are querying to the same table than your "ModelName" model?
Anyway, it's redundant to specify the 'id' field since it comes by default with all the django models.
Upvotes: 2