Django / Python:原始SQL查询-错误绑定参数

我很难弄清楚为什么我要针对的SQL似乎有效时为什么收到以下错误。有任何想法吗?谢谢!

sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.

这是我的原始SQL查询:

entries = Entry.objects.raw("SELECT * FROM learning_logs_entry LEFT JOIN learning_logs_document ON (learning_logs_entry.id = learning_logs_document.entry_id) WHERE learning_logs_entry.topic_id = %s AND learning_logs_entry.tag_id IN %s ORDER BY learning_logs_entry.date_added DESC", params=[topic_id, (1,2,3)])

这是产生的SQL查询:

SELECT * FROM learning_logs_entry LEFT JOIN learning_logs_document ON (learning_logs_entry.id = learning_logs_document.entry_id) WHERE learning_logs_entry.topic_id = 1 AND learning_logs_entry.tag_id IN (1, 2, 3) ORDER BY learning_logs_entry.date_added DESC

这是我的Entry和Tag模型:

class Entry(models.Model):
    topic = models.ForeignKey(Topic,on_delete=models.CASCADE, related_name='entries') 
    text = models.TextField(validators=[validate_text])
    date_added = models.DateTimeField(auto_now_add=True)
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta: #metadata
        verbose_name_plural = 'entries'

class Tag(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

class Document(models.Model):
    docfile = models.ImageField(upload_to='files/', blank=True, null=True)
    entry = models.ForeignKey(Entry, on_delete=models.CASCADE, null=True)
评论
  • 娇气的小奶包
    娇气的小奶包 回复

    请不要使用原始查询,除非这是Django ORM无法(有效地)完成的事情。

    但是,这可以使用Django ORM有效地完成,例如:

    Entry.objects.filter(
        tag_id__in=[1,2,3]
        topic_id=topic_id    
    ).prefetch_related('document_set').order_by('-date_added')

    The .prefetch_related will make an extra query, but this will reduce the amount of bandwidth, since if this is done in a JOIN, the same record of entry can be returned multiple times, that could result in transmitting the same data hundreds of times.