Reputation: 409
I have multiple columns in a model. I am attaching a screenshot:
I can search only IP address but I also want to search in Department and location. Any idea how to solve this, here is my admin.py looks like:
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']
Following line is giving me error:
search_fields = ['ipaddress','department', 'location',]
The error i am seeing is:
C:\Users\mohiuddin_rana\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py", line 1087, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains [23/Sep/2018 23:45:19] "GET /admin/pages/ipaddress/?q=dev HTTP/1.1" 500 155606
Here is the IP model in python.py
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]
How to search in multiple columns?
Upvotes: 0
Views: 1458
Reputation: 1162
In your Ipaddress model, location and department are foreign keys on which you want to search. To specify search on foreign key field you have to specify the field on that model as :
search_fields = ['foreign_key__related_fieldname']
as given in the docs.
In your case it could be location__name and department__name , if you want to search by their names.
Upvotes: 1