我可以对 Django 中的外键字段使用什么类型的查找

What type of lookup can i use for a foreign key field in django

我的应用程序中有一个搜索表单。我正在我的应用程序的数据库中用它执行一些请求。

类别字段在我的应用程序中是一个外键关系。尝试进行搜索时,我收到此错误,因为该类别是一个 foeirgn 键,也许我为此使用了错误的查找表达式。请问正确的方法是什么?谢谢

错误日志

Exception Type: FieldError at /searchproduct/
Exception Value: Related Field got invalid lookup: icontains

models.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)

views.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)

您可能想在其中一个相关字段上使用查找(我相信这里是 categoryname 字段)。使用 __ 遍历查找中的关系。 queryset1 or queryset2 也没有多大意义。您想在查询中使用 OR 吗?为此使用 Q objects [Django docs]

from django.db.models import Q

products = Product.objects.filter(Q(category__name__icontains=product_name) | Q(name__icontains=product_name))

我能够使用上面的 seluk 评论解决它。

因为我想查询的是Category的名称,所以我简单地使用了查询category__name__icontains=product_name

views.py

def search(request):
    if request.method == 'GET':      
        product_name =  request.GET.get('search')    
        products = Product.objects.filter(category__name__icontains=product_name) or Product.objects.filter(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)