[Answered ]-Raw query must include the primary key error even though I'm doing SELECT *

0👍

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)
👤gema

2👍

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.

Leave a comment