今天在设置django的搜索框搜索条件时,外键的不能直接像字符串类型那样直接写search_field中,但是我又想让他通过外键关联的数据条件搜索,
参考http://www.voidcn.com/article/p-gsdvpisv-bau.html
可以设置按照所关联的数据中某个字段搜索,比如我有两个表,一个收藏记录表(Collect),一个用户表(Userprofile),我想让人能够通过用户表中的用户姓名来搜索收藏记录,可以设置为
在models.py中:
class UserProfile(Base): '''用户信息''' name = models.CharField('名字', max_length=255, default='')
class Collect(Base): '''收藏记录''' user = models.ForeignKey(UserProfile, verbose_name='收藏者', on_delete=models.DO_NOTHING)
在admin.py中:
search_fields = ('user__phone', )
这样就可以通过用户名字搜索收藏记录了。