我得到这个错误django.core.exceptions.FieldError:ForeignKey或join不支持在不允许的字段上查找“icontains”

hpxqektj  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(322)

我得到这个错误django.core.exceptions.FieldError:ForeignKey或join不支持在不允许的字段上查找“icontains”
下面是models.py

class Author(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    
    def __str__(self):
        return self.first_name + ' ' + self.last_name
    
class Book(models.Model):
    title = models.CharField(max_length=100)
    rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
    author = models.ForeignKey(Author,on_delete=models.CASCADE,null=True)
    is_bestselling = models.BooleanField(default=False)
    slug = models.SlugField(default="",null=False,blank=True)

    def get_absolute_url(self):
        return reverse("model_detail", args=[self.slug])    
    
    def __str__(self):
        return self.title

下面是admin.py

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'rating', 'author','is_bestselling',)
    list_display_links = ('title', 'rating',)
    search_fields = ('title', 'rating','author',)
    list_filter = ('rating', 'is_bestselling',)
    prepopulated_fields = {
        'slug': ('title',)
    }

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name',)
    list_display_links = ('first_name', 'last_name',)
    search_fields = ('first_name', 'last_name',)

我试图在我的图书模型中搜索作者。

1bqhqjot

1bqhqjot1#

下面是答案:
要解决此问题,可以修改search_fields属性,改为搜索Author模型的相关字段。下面是我的BookAdmin类的更新版本:

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'rating', 'author', 'is_bestselling',)
    list_display_links = ('title', 'rating',)
    search_fields = ('title', 'rating', 'author__first_name', 'author__last_name',)
    list_filter = ('rating', 'is_bestselling',)
    prepopulated_fields = {
        'slug': ('title',)
    }

在修改后的search_fields中,“author__first_name”和“author__last_name”用于搜索相关Author模型的first_name和last_name字段。语法用于遍历Book和Author模型之间的关系。
通过显式指定相关字段,您可以使用“icontains”查找对Author模型的first_name和last_name字段执行不区分大小写的搜索。
进行此更改后,您应该能够根据作者的名字或姓氏搜索书籍,而不会遇到与不支持的查找相关的FieldError。

相关问题