【问题标题】:Raw query must include the primary key error even though I'm doing SELECT *即使我正在执行 SELECT *,原始查询也必须包含主键错误
【发布时间】:2017-06-29 09:34:48
【问题描述】:

按照https://docs.djangoproject.com/en/1.10/topics/db/sql/

我有

query = "SELECT * FROM model_name"
objs = []
for obj in models.ModelName.objects.raw(query):
    objs.append(obj)

但它抱怨原始查询必须包含主键错误

为什么会这样

型号代码:

class ModelName(ModelBase):
    fielda = models.CharField(max_length=255)

class ModelBase(models.Model):
    id = models.IntegerField(primary_key=True)

【问题讨论】:

  • 不要使用原始查询。我还没有发现 ORM 不能做的任何事情,而且我已经编写了一些复杂的查询。如果我在 Django 应用程序中看到这样的原始查询,我会认为开发人员不知道他们在做什么。

标签: python mysql django python-3.x django-models


【解决方案1】:

根据您的问题,您的表名可能有问题。 Django 表约定如下:

appname_modelname

所以说你有投票应用 和里面的轮询模型类 民意调查/models.py

class Poll(models.Model):
    title = models....

那么你在 sql 中的表名将是 polls_poll。

最好先明确导入模型以避免混淆。

from polls.models import Poll

query = "SELECT * FROM polls_poll"
objs = []
for obj in Poll.objects.raw(query):
    objs.append(obj)

所以在你的情况下查询应该是

select * from MyApp_ModelName;

我认为对于主键问题,如果您不打算使用 CharField "prod001" 之类的东西,那么 AutoField 是一种方法。

否则在您的模型中 在 models.py 中尝试这个解决方案。只是为了确保您的 primary_key 是唯一的。

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)

【讨论】:

    【解决方案2】:

    您确定查询的是与“ModelName”模型相同的表吗?

    无论如何,指定 'id' 字段是多余的,因为它默认与所有 django 模型一起提供。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-30
      • 2014-01-21
      • 2020-05-09
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2015-12-30
      相关资源
      最近更新 更多