首页 > 解决方案 > 我可以对 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)

标签: pythondjangodjango-modelsdjango-viewslookup

解决方案


您可能希望在相关字段之一上使用查找(我相信这里的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))

推荐阅读