Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django search_fields foreign key not working

I have these two models :

class Module(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(unique=True, max_length=255)

class Subject(models.Model):
    id = models.AutoField(primary_key=True)
    module = models.ForeignKey(Module)

I then created ModelAdmin:

class SubjectAdmin(admin.ModelAdmin):
    list_display = ('module', 'name', 'enabled',)
    list_filter = ('module', 'name',)
    search_fields = ('module', 'name',)

But I cannot filter or search by module.

like image 634
kelvinfix Avatar asked Nov 30 '22 16:11

kelvinfix


2 Answers

Did you register the ModelAdmin?

admin.site.register(Subject, SubjectAdmin)

You might also want to try either giving module a __unicode__ method, or using relationship spanning.

list_filter = ('module__name', 'name',)

# or...
# within Module
def __unicode__(self):
    return self.name
like image 167
Josh Smeaton Avatar answered Dec 06 '22 22:12

Josh Smeaton


For refrencing foreign key use __

Example if you want name of module:

class Module(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(unique=True, max_length=255)

    def __unicode__(self):
        return self.name:

class SubjectAdmin(admin.ModelAdmin):
    list_display = ('module', 'name', 'enabled',)
    list_filter = ('module__name', 'name',)
    search_fields = ('module__name', 'name',)
like image 32
Avinash Garg Avatar answered Dec 06 '22 20:12

Avinash Garg