Search code examples
pythondjangodjango-adminsearch-form

Django search_field


How to solve this error? cause whenever I search the student user I received an error, enter image description here

error

enter image description here

admin.py

@admin.register(StudentsEnrollmentRecord)
class StudentsEnrollmentRecordAdmin(admin.ModelAdmin):
    #inlines = [InLineSubject]
    list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year')
    #list_select_related = ('Student_Users')
    ordering = ('Education_Levels','Student_Users__lrn')
    list_filter = ('Student_Users','Education_Levels','Section','Payment_Type')
    search_fields = ('Student_Users',)


    def lrn(self, obj):
        return  obj.Student_Users.lrn

my models.py

class StudentsEnrollmentRecord(models.Model):
    Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True)
    School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True)
    Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True)
    Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True)

UPDATE models

class StudentProfile(models.Model):
   lrn = models.CharField(max_length=500,null=True)
   Firstname = models.CharField(max_length=500,null=True,blank=True)
   Middle_Initial = models.CharField(max_length=500,null=True,blank=True)
   Lastname = models.CharField(max_length=500,null=True,blank=True)
   Education_Levels= models.ForeignKey(EducationLevel, on_delete=models.CASCADE,blank=True,null=True)

Solution

  • You need to provide a specific field from StudentProfile - currently your search field is

    search_fields = ('Student_Users',)
    

    which means only the model itself. You didn't post a schema of your StudentProfile, but for example if it contains a Lastname field, you should use it like this:

    search_fields = ('Student_Users__Lastname',)
    

    To include multiple fields you can do

    search_fields = ('Student_Users__Lastname', 'Student_Users__Firstname',)
    

    You could also do

    search_fields = ('=Student_Users__Lastname',)
    

    to match the last name "exactly", previous example checks whether the field contains the query string