Django 管理:搜索外键对象而不是
我的模型如下所示:
class Asset(models.Model):
serial_number = models.CharField(max_length=100, unique=True)
asset_tag = models.CharField(max_length=100, unique=True)
class WorkOrder(models.Model):
asset = models.ForeignKey(Asset)
本质上,提交工作订单,然后管理员将资产分配给工作订单。 asset_tag 字段是我们可以扫描的条形码。在 Django 后台编辑工单时,默认情况下 asset 字段显示为 选择>
小部件。我们想要做的是拥有一个搜索字段,以便我们可以扫描资产标签,然后在数据库中搜索正确的资产以与工作订单关联。
我知道您可以将 Django 管理外键自定义为硬编码查询,但我不知道如何获取它,因此它根据管理页面上的字段进行搜索。
My model looks like this:
class Asset(models.Model):
serial_number = models.CharField(max_length=100, unique=True)
asset_tag = models.CharField(max_length=100, unique=True)
class WorkOrder(models.Model):
asset = models.ForeignKey(Asset)
Essentially, a work order is submitted and then an admin assigns an asset to the work order. The asset_tag
field is a barcode that we can scan in. When editing the work order in the Django admin, by default the asset
field is displayed as a <select>
widget. What we want to be able to do is have a search field so that we can scan the asset tag and then search for the right asset in the DB to associate with the work order.
I know you can customize the Django admin foreign key to a hard coded query, but I can't figure out how to get it so it does a search based on a field on the admin page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 Django >= 2.0,您可以利用名为
autocomplete_fields
。您必须在相关对象的 ModelAdmin 上定义search_fields
,因为自动完成搜索会使用它。由于您与
WorkOrder
中的Asset
存在ForeignKey
关系,因此在应用的admin.py
中添加以下内容:将要用于搜索的字段添加到
search_fields
中,并添加定义autocomplete_fields
如上面的代码所示。If you are using Django >= 2.0, you can take advantage of a feature called
autocomplete_fields
. You must definesearch_fields
on the related object’s ModelAdmin because the autocomplete search uses it.Since you have a
ForeignKey
relationship toAsset
inWorkOrder
, in theadmin.py
of your app add the following:Add the fields you want to use for searching to
search_fields
, and add defineautocomplete_fields
as shown in the code above.现在您可以使用
autocomplete_fields
来自 django 2.0。非常整洁。
Now you can use the
autocomplete_fields
from django 2.0.It's quite neat.
您是否看过
raw_id_fields
?它应该非常接近你所追求的。
Did you take a look at
raw_id_fields
?It should be pretty to close to what you're after.