In my application there are fields like phone, username, Address, id. but i need only details of "username" field when i search it in search box. how we can do this . can anyone help me with DJango code
CodePudding user response:
Are you doing search system? If you do, so use get_queryset(self). That will return username, that you search. And get_context_data()
def get_queryset(self):
return User.objects.filter(username__icontains=self.request.GET.get("q"))
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["q"] = f'q={self.request.GET.get("q")}&'
return context
Write down this one into your view, where is your search app. in template, search form must have name='q'
CodePudding user response:
Assume you have a model named class Department(models.Model)
with 2 fields (name, description) in models.py
like this:
from django.db import models
class Department(models.Model):
DEPT_NAME = (
('Staff', 'Staff'),
('Manager', 'Manager'),
)
name = models.CharField(max_length=15, choices=DEPT_NAME)
description = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.name
At Django admin page you only want search result of name
field.
In your admin.py
, use the search_fields attribute of the ModelAdmin
:
from django.contrib import admin
from .models import *
@admin.register(Department)
class DepartmentAdmin(admin.ModelAdmin):
DEPT_NAME = (
('Staff', 'Staff'),
('Manager', 'Manager'),
)
name = models.CharField(max_length=15, choices=DEPT_NAME)
description = models.CharField(max_length=100, null=True, blank=True)
search_fields = ('id', 'name',) # <-- Choose any field you want Django search