python - 相关字段的查询无效: blog_posts_name

标签 python django python-3.x error-handling django-admin-filters

我正在尝试将作者添加到search_field中,但是会引发错误-相关字段查找无效:​​icontains

models.py

class Post(models.Model):
STATUS_CHOICES = (
    ('draft', 'Draft'),
    ('published', 'Published'),
    )
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,unique_for_date='publish')
author = models.ForeignKey(User,
on_delete=models.CASCADE,related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
    default='draft')

class Meta:
    ordering = ('-publish',)

def __str__(self):
    return self.title

管理员
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'author', 'publish',
    'status')
    list_filter = ('status', 'created', 'publish', 'author')
    search_fields = ('title', 'body','status','author__blog_posts_name')
    prepopulated_fields = {'slug': ('title',)}
    raw_id_fields = ('author',)
    date_hierarchy = 'publish'
    ordering = ('status', 'publish')

我已经尝试过 search_fields = ('author','foreinkeyfield__author','author__name','author__User_name',)

根据用户在先前回答的问题中提出的建议,但似乎没有一个起作用。

最佳答案

Django's User model具有以下字段(以及其他一些与按名称搜索不相关的字段):

  • username
  • first_name
  • last_name
  • email

  • 您只能在查找中使用现有字段,而列出的字段不会引用任何有效的DB字段。

    以上字段的查找如下所示:
    search_fields = (
        'author__username',
        'author__first_name',
        'author__last_name',
        'author__email',
    )
    

    关于python - 相关字段的查询无效: blog_posts_name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59631981/

    相关文章:

    python - unittest.TestCase 的子类的子类,具有不同的 setUpClass 类方法

    Python3 PyGame 如何移动图像?

    python - 使用正则表达式从字符串中仅提取 Unicode 字符

    python - 如何制作 tkinter 条目小部件?

    python - 初始化器与构造器

    python - 如何在我的虚拟环境中使用 Python 3 (3.5) 作为默认解释器?

    django - 测试 Django ModelForm 是否有实例

    python - 使用 REST 在服务器端保存数据

    c++ - fatal error : eigen3/Eigen/Core: No such file or directory

    python - 创建具有连续整数但忽略特定数字的 numpy 数组的最快方法