django sql .raw过滤一个字符串不工作

6xfqseft  于 2023-01-31  发布在  Go
关注(0)|答案(3)|浏览(101)

我试图筛选外键,但得到一个错误。
当前代码为:
views.py

def kingmailboxcodesshow(request):
    lname = "King"
    lockbox_list = MailBoxCodes.objects.raw('SELECT * FROM mailboxcodes WHERE Address_id__contains %s',[lname])
    return render(request,"users/mailboxcodesshow.html",{'MailBoxCodes':lockbox_list})
models.py
from django.db import models
from properties.models import Properties, Building_Name
from django.db.models import Q

# Create your models here.

class MailBoxCodes(models.Model):
   id = models.AutoField(primary_key=True)
   Address = models.ForeignKey(Properties, max_length=10, on_delete=models.CASCADE, default='Unknown',limit_choices_to=Q(StudentRental=True)| Q(Active=True))
   MailBoxCode = models.CharField(max_length=10, null=False,default='000')
   Active = models.BooleanField(default=True)

   class Meta:
      db_table = "mailboxcodes"

   def __str__(self):
      return str(self.Address)

收到此错误:

django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''King'' at line 1")

我仍然是django和python的新手,看着这个错误,我想我需要少一些"围绕国王",但我不确定如何实现这一点。
我在Address_id中有一堆地址,我只想检索街道地址中包含work King的所有地址。

lnlaulya

lnlaulya1#

Django最大的好处是你不需要原始的SQL查询,除非你真的知道你在做什么。请按照官方教程,因为它解释了Django的基本原理,并将指导你通过这里:Django tutorial
为了帮助您解决此特定问题:

def kingmailboxcodesshow(request):
    lname = "King"
    lockbox_list = MailBoxCodes.objects.filter(address__name__contains=lname)
    return render(request,"users/mailboxcodesshow.html",{'MailBoxCodes':lockbox_list})
o3imoua4

o3imoua42#

在SQL中没有__contains这样的东西,它只是一些Django逻辑将其转换为查询,您可以使用:

def kingmailboxcodesshow(request):
    lname = 'King'
    lockbox_list = MailBoxCodes.objects.raw(
        'SELECT * FROM mailboxcodes WHERE Address_id LIKE %%%s%%', (lname,)
    )
    return render(
        request, 'users/mailboxcodesshow.html', {'MailBoxCodes': lockbox_list}
    )

也就是说,使用原始查询应该是最后的手段:Django的ORM的整个思想是,正如你在这个问题中所发现的,抽象查询逻辑。你可以用以下代码运行它:

def kingmailboxcodesshow(request):
    lname = 'King'
    lockbox_list = MailBoxCodes.objects.filter(Address_id__contains=lname)
    return render(
        request, 'users/mailboxcodesshow.html', {'MailBoxCodes': lockbox_list}
    )
ybzsozfc

ybzsozfc3#

请分享您的MailBoxCodes模型,并告诉什么是这个Address_id,因为你提到它是一个外键在上面的评论之一。
试试这个:

def kingmailboxcodesshow(request):
    lname = 'King'
    lockbox_list = MailBoxCodes.objects.filter(Address__name__contains=lname)
    return render(
        request, 'users/mailboxcodesshow.html', {'MailBoxCodes': lockbox_list}
    )

或者这个:

MailBoxCodes.objects.filter(Address__contains=lname)

您还可以使用__icontains查找进行不区分大小写的过滤。

相关问题