python - 我可以对 django 中的外键字段使用什么类型的查找
问题描述
我的应用程序中有一个搜索表。我正在我的应用程序的数据库中执行一些请求。
类别字段是我的应用程序中的外键关系。尝试进行搜索时,我收到此错误,因为类别是 foeirgn 键,也许我为此使用了错误的查找表达式。请问我该怎么做的正确方法是什么?谢谢
错误日志
Exception Type: FieldError at /searchproduct/
Exception Value: Related Field got invalid lookup: icontains
模型.py
from django_countries.fields import CountryField
class Category(models.Model):
name = models.CharField(max_length=256)
class Product(models.Model):
name = models.CharField(max_length=36)
price = models.PositiveIntegerField()
description = models.TextField()
country = CountryField(blank_label='(select country)')
category = models.ForeignKey(Category, on_delete=models.CASCADE)
视图.py
def search(request):
if request.method == 'GET':
product_name = request.GET.get('search')
products = Product.objects.filter(Q(category__name__icontains=product_name) | Q(country__name__icontains=product_name) | Q(name__icontains=product_name))
context = {"products": products}
return render(request, "core/search.html", context)
else:
result = "Sorry there is no product with that name"
return render(request, "core/search.html", context)
解决方案
您可能希望在相关字段之一上使用查找(我相信这里的name
字段category
)。用于__
遍历查找中的关系。也queryset1 or queryset2
没有多大意义。您想在查询中使用 OR 吗?为此使用Q
对象 [Django docs]:
from django.db.models import Q
products = Product.objects.filter(Q(category__name__icontains=product_name) | Q(name__icontains=product_name))
推荐阅读
- powershell - 没有 OutFile 的调用 WebRequest?
- node.js - 即使我启用了 lib `es2019`,为什么我在 TypeScript 中没有可用的 Array.prototype.flat?
- python - 从一个范围内获取 n 个数字,包括 x
- macos - 如何在 macOS 上将“\x”插入到 hexdump 格式字符串中?
- spring - 遇到无效的@Scheduled 方法'methodName':只有无参数方法可以用@Scheduled 注释
- python - 计算缺失年份的同比值
- go - 如何在文件和结构中设置日期和日期数组
- python - 麻线上传区 收到错误“是版本的无效值”
- angular - 使用 @Inputs 的角度扩展指令
- firebase - 无法在 firebase 上部署 vue.js 应用程序 - 错误:任务失败