Django - 搜索相关字段
我的模型:
class Contact(models.Model):
first_name = models.CharField(_("First name"), max_length=30, )
last_name = models.CharField(_("Last name"), max_length=30, )
email = models.EmailField(_("Email"), blank=True, max_length=75)
class PhoneNumber(models.Model):
contact = models.ForeignKey(Contact)
phone = models.CharField(_("Phone Number"), blank=True, max_length=30, )
primary = models.BooleanField(_("Primary"), default=False)
我的 admin.py:
class ContactOptions(AutocompleteAdmin):
list_display = ('last_name', 'first_name')
ordering = ['last_name']
search_fields = ('first_name', 'last_name', 'email')
related_search_fields = { """??? I want to search the Phone Numbers ???""" }
如何在 Django 管理中搜索电话号码?请给一些代码。非常感谢!
My models:
class Contact(models.Model):
first_name = models.CharField(_("First name"), max_length=30, )
last_name = models.CharField(_("Last name"), max_length=30, )
email = models.EmailField(_("Email"), blank=True, max_length=75)
class PhoneNumber(models.Model):
contact = models.ForeignKey(Contact)
phone = models.CharField(_("Phone Number"), blank=True, max_length=30, )
primary = models.BooleanField(_("Primary"), default=False)
My admin.py:
class ContactOptions(AutocompleteAdmin):
list_display = ('last_name', 'first_name')
ordering = ['last_name']
search_fields = ('first_name', 'last_name', 'email')
related_search_fields = { """??? I want to search the Phone Numbers ???""" }
How to search the Phone Numbers in Django admin? Please give some code. Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以防万一有人遇到这个问题,在 Django 1.6 中,反向关系搜索确实是可能的。
在你的手机模型中添加 lated_name="phonesList" 到联系人字段
现在在 search_field 中你可以使用双下划线从 contct 转到电话,如下所示:
phonesList__phone
Just in case someone comes over this question, in Django 1.6, search in reverse relation is indeed possible.
In your phone model add related_name="phonesList" to contact field
Now in search_field you can use the double undescore to go from conatct to phones like this:
phonesList__phone
更新:这个答案已经过时,请参阅 来自 elsadek 的答案 相反,
您要求能够遵循反向关系(即,从 PhoneNumber 回到 Contact),但我不相信跨表的双下划线
__
技巧在这里起作用。如果您的联系人拥有 PhoneNumber 模型的密钥而不是当前设置:
那么在管理配置中您可以执行以下操作:
UPDATE: this answer is outmoded, see the answer from elsadek instead
You're asking to be able to follow a reverse relation (ie, from PhoneNumber back to Contact) but I don't believe the double-underscore
__
trick for spanning tables will work here.If your Contact had the key to the PhoneNumber model instead of the current set-up:
then in the admin config you could do: