【发布时间】:2019-08-17 00:22:36
【问题描述】:
我尝试在 Django 中运行一个原始 SQL 查询。当我显示 RawQuerySet 对象时,它显示了正确的查询,但没有返回任何输出。
我已尝试将参数转换为字符串,并尝试将引号附加到参数,但没有奏效。
我也尝试过相同的查询,但我对参数进行了硬编码。那行得通。
我也打开了 dbshell 来尝试查看查询是否返回输出。它也很好用。
这是我在我的 dbshell 中运行的:
select id FROM recommender_item WHERE
id in (select item_id from
recommender_item_likes where user_id = 1)
and color = 'Black';
请注意,以下查询无效:
select id FROM recommender_item WHERE
id in (select item_id from
recommender_item_likes where user_id = 1)
and color = Black;
这是我要运行的实际查询:
Item.objects.raw('select id FROM recommender_item WHERE
id in (select item_id from recommender_item_likes where
user_id = %s) and %s = %s', [request.user.id, user_pref, pref_choice,])
这是与硬编码参数相同的查询:
Item.objects.raw('select id FROM recommender_item WHERE
id in (select item_id from recommender_item_likes where user_id = %s)
and color = "Black"', [request.user.id])
我的模板中的输出应该只是这个 id 列表: 1、64、437、1507、1685
但是,现在它只返回 []
这分别是两种情况下的 RawQuerySet 对象:
<RawQuerySet: select id FROM recommender_item WHERE
id in (select item_id from recommender_item_likes where user_id = 1)
and color = Black>
和
<RawQuerySet: select id FROM recommender_item WHERE
id in (select item_id from recommender_item_likes where user_id = 1)
and color = "Black">
正在执行的实际 SQL 查询,从 Django 调试工具栏中检索:
select id FROM recommender_item WHERE
id in (select item_id from recommender_item_likes where
user_id = '1') and '''color''' = '''"Black"'''
models.py
class Item(models.Model):
#id = models.UUIDField(primary_key = True, default = uuid.uuid4, help_text = 'Unique ID for this particular item')
item_type = models.CharField(max_length = 200, null = True, blank = True)
price = models.CharField(max_length = 200, null = True, blank = True)
color = models.CharField(max_length = 200, null = True, blank = True)
image_URL = models.CharField(max_length = 1000, null = True, blank = True)
fit = models.CharField(max_length = 200, null = True, blank = True)
occasion = models.CharField(max_length = 200, null = True, blank = True)
brand = models.CharField(max_length = 200, null = True, blank = True)
pattern = models.CharField(max_length = 200, null = True, blank = True)
fabric = models.CharField(max_length = 200, null = True, blank = True)
length = models.CharField(max_length = 200, null = True, blank = True)
likes = models.ManyToManyField(User, blank = True, related_name = 'item_likes')
【问题讨论】:
-
如果你格式化你的代码行以防止水平滚动,它会更容易提供帮助。
-
对不起!编辑代码使其更易于阅读
-
我认为
RawQuerySet.__repr__的输出具有误导性。如果您检查实际的查询(使用django.db.connection.queries),您会发现与 RawQuerySet 输出相反,在发送到数据库的 SQL 中引用了字符串参数。不过,不确定这对您来说意味着什么;看来,如果您的硬编码查询有效,那么参数化查询也应该有效。 -
所以我发现实际查询是通过 django 调试工具栏执行的。是这样的:
select id FROM recommender_item WHERE id in (select item_id from recommender_item_likes where user_id = '1') and '''color''' = '''"Black"'''我不知道这是否会有所帮助。 -
我现在已经尝试过使用 Sqlite,它工作得很好,字符串参数被单引号引起来,例如
WHERE color = 'black'(尽管 DDT 显示三重引号而不是单引号)。我正在使用 Django 2.1.7;也许早期版本存在问题。你的版本是什么?
标签: sql django sqlite django-models django-orm