【问题标题】:Related Field got invalid lookup: blog_posts_name相关字段查找无效:​​blog_posts_name
【发布时间】:2020-04-25 04:05:11
【问题描述】:

我正在尝试将 author 添加到 search_field 但它抛出了错误-Related Field got invalid lookup: 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.py

@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',)

根据用户在之前回答的问题中的建议,但它们似乎都没有工作。

【问题讨论】:

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


    【解决方案1】:

    Django's User model 具有以下字段(以及其他可能与按名称搜索无关的字段):

    • username
    • first_name
    • last_name
    • email

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

    上述字段的查找如下所示:

    search_fields = (
        'author__username',
        'author__first_name',
        'author__last_name',
        'author__email',
    )
    

    【讨论】:

    • 已尝试但未显示所需的输出。我使用电子邮件地址查找该用户的帖子,但输出不正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多