如何使用search_fields

时间:2018-09-24 03:46:50

标签: python django django-models

我在一个模型中有多个列。我要附上屏幕截图: enter image description here

我只能搜索IP地址,但我也想在部门和位置中搜索。任何想法如何解决这个问题,这是我的admin.py如下:

from django.contrib import admin
from pages.models import Post, Device, DeviceType, DeviceModel, Ipaddress, DeviceGroup, Location,Department,Comment
from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter


class IpaddressAdmin(admin.ModelAdmin):
        prepopulated_fields = {'slug': ('ipaddress',)}

        search_fields = ['ipaddress','department', 'location',]


        list_display = ('ipaddress', 'machinename', 'user', 'department','location','updated',)
        list_display_links =('ipaddress', 'machinename', 'user', 'department','location','updated',)

#        autocomplete_fields = ['department', 'location',]


        list_filter = (
        ('user', DropdownFilter),
        ('department', RelatedDropdownFilter),
        ('location', RelatedDropdownFilter),

    )
        list_per_page = 100

class DepartmentAdmin(admin.ModelAdmin):
    search_fields = ['name']

class LocationAdmin(admin.ModelAdmin):
    search_fields = ['description']   

以下一行给我错误:

search_fields = ['ipaddress','department', 'location',]

我看到的错误是:

  

C:\ Users \ mohiuddin_rana \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ django \ db \ models \ sql \ query.py“,行1087,在build_lookup中           引发FieldError('相关字段的查询无效:{}'。format(lookup_name))       django.core.exceptions.FieldError:相关字段的查找无效:​​icontains       [23 / Sep / 2018 23:45:19]“ GET / admin / pages / ipaddress /?q = dev HTTP / 1.1” 500 155606

这是python.py中的IP模型

lass Ipaddress(models.Model):
    ipaddress=models.CharField("Ip Address",max_length=20)
    slug = models.SlugField(unique=True)
    machinename=models.CharField("Machine Name",max_length=500)
    user=models.CharField("User",max_length=200)
    department= models.ForeignKey("Department", on_delete=models.CASCADE)
    location= models.ForeignKey("Location", on_delete=models.CASCADE)
    updated = models.DateField("Date Updated",null=True)
    note =models.TextField()
    class Meta:
       verbose_name = 'IP Management'

    def __str__(self):
        return self.ipaddress[:50]

如何在多列中搜索?

1 个答案:

答案 0 :(得分:0)

在您的Ipaddress模型中,位置部门是您要搜索的外键。要在外键字段上指定搜索,您必须将该模型上的字段指定为:

search_fields = ['foreign_key__related_fieldname']

docs中所述。

如果要按名称搜索,可能是location__name和department__name。