开发者

Django search_fields foreign key not working

I have t开发者_开发百科hese 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.


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


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',)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜