在 search_fields 中正确使用外键引用,Django 管理
Properly using Foreign Key references in search_fields, Django admin
我遇到了一个奇怪的难题,我需要在 Django 1.8.4 中使用虚拟环境中的 python 3.4 获得一些帮助。
我在 2 个不同的应用程序中有 2 个模型...如下所示,有多个外键引用。
库存应用程序
class InventoryItem(models.Model):
item_unique_code = models.CharField(max_length=256, blank=False, null=False)
category = models.CharField(max_length=256, blank=False, null=False,choices=[('RAW','Raw Material'),('FG','Finished Good'),('PKG','Packaging')])
name = models.CharField(max_length=64, blank=False, null=False)
supplier = models.CharField(max_length=96, blank=False,null=False)
approved_by = models.CharField(max_length=64, editable=False)
date_approved = models.DateTimeField(auto_now_add=True, editable=False)
comments = models.TextField(blank=True, null=True)
def __str__(self):
return "%s | %s | %s" % (self.item_unique_code,self.name,self.supplier)
class Meta:
managed = True
unique_together = (('item_unique_code', 'category', 'name', 'supplier'),)
食谱应用程序
class RecipeControl(models.Model):
#recipe_name choice field needs to be a query set of all records containing "FG-Finished Goods"
recipe_name = models.ForeignKey(items.InventoryItem, related_name='recipe_name', limit_choices_to={'category': 'FG'})
customer = models.ForeignKey(customers.CustomerProfile, related_name='customer')
ingredient = models.ForeignKey(items.InventoryItem, related_name='ingredient')
min_weight = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
max_weight = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
active_recipe = models.BooleanField(default=False)
active_by = models.CharField(max_length=64, editable=False)
revision = models.IntegerField(default=0)
last_updated = models.DateTimeField(auto_now_add=True, editable=False)
def __str__(self):
return "%s" % (self.recipe_name)
class Meta:
managed = True
unique_together = (('recipe_name', 'customer', 'ingredient'),)
我在食谱的管理中得到了一些奇怪的结果class...
from django.contrib import admin
from django.contrib.auth.models import User
from .models import RecipeControl
from Inventory import models
class RecipeView(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.active_by = request.user.username
obj.save()
fieldsets = [
('Recipe Information', {'fields': ['recipe_name', 'customer']}),
('Ingredients', {'fields': ['ingredient','min_weight','max_weight','active_recipe']}),
('Audit Trail', {'fields': ['active_by','revision','last_updated'],'classes':['collaspe']}),
]
list_select_related = ['recipe_name','customer','ingredient']
search_fields = ['recipe_name','customer','ingredient','active_by']
readonly_fields = ('last_updated','active_by')
list_display = ['recipe_name','customer','ingredient','min_weight','max_weight','last_updated','active_by', 'active_recipe']
admin.site.register(RecipeControl, RecipeView)
我遇到的问题是,如果我尝试在任何 ForeignKey 字段上进行搜索,Django 会抛出此错误...
Exception Type: TypeError at /admin/Recipe/recipecontrol/
Exception Value: Related Field got invalid lookup: icontains
根据 Django Admin Doc's 和其他有关 Whosebug 的旧问题,它说我应该按照 search_fields = ['inventoryitem__name' ] 但我认为这是对同一个应用程序中 FK 的引用 model.py。
是否有更正确的方法 referencing/importing 来自其他应用程序的其他模型,我丢失了,或者我是否必须使用某种可调用方法魔术来使搜索功能正确查找?我尝试了多种不同的组合,但似乎没有任何效果。我对 Django 比较陌生,所以我相信它很简单。
您应该使用双下划线符号来搜索相关对象的字段。但是,您应该使用外键字段的名称(例如 recipe_name
),而不是模型的名称(例如 InventoryItem
)。外键的模型是否在同一个应用程序中并不重要。例如:
search_fields = ['recipe_name__name']
请注意,如果您想搜索 recipe_name 和成分字段,您需要包括这两个字段,即使它们是同一模型的外键。
search_fields = ['recipe_name__name', 'ingredient__name']
我遇到了一个奇怪的难题,我需要在 Django 1.8.4 中使用虚拟环境中的 python 3.4 获得一些帮助。
我在 2 个不同的应用程序中有 2 个模型...如下所示,有多个外键引用。
库存应用程序
class InventoryItem(models.Model):
item_unique_code = models.CharField(max_length=256, blank=False, null=False)
category = models.CharField(max_length=256, blank=False, null=False,choices=[('RAW','Raw Material'),('FG','Finished Good'),('PKG','Packaging')])
name = models.CharField(max_length=64, blank=False, null=False)
supplier = models.CharField(max_length=96, blank=False,null=False)
approved_by = models.CharField(max_length=64, editable=False)
date_approved = models.DateTimeField(auto_now_add=True, editable=False)
comments = models.TextField(blank=True, null=True)
def __str__(self):
return "%s | %s | %s" % (self.item_unique_code,self.name,self.supplier)
class Meta:
managed = True
unique_together = (('item_unique_code', 'category', 'name', 'supplier'),)
食谱应用程序
class RecipeControl(models.Model):
#recipe_name choice field needs to be a query set of all records containing "FG-Finished Goods"
recipe_name = models.ForeignKey(items.InventoryItem, related_name='recipe_name', limit_choices_to={'category': 'FG'})
customer = models.ForeignKey(customers.CustomerProfile, related_name='customer')
ingredient = models.ForeignKey(items.InventoryItem, related_name='ingredient')
min_weight = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
max_weight = models.DecimalField(max_digits=16, decimal_places=2, blank=True, null=True)
active_recipe = models.BooleanField(default=False)
active_by = models.CharField(max_length=64, editable=False)
revision = models.IntegerField(default=0)
last_updated = models.DateTimeField(auto_now_add=True, editable=False)
def __str__(self):
return "%s" % (self.recipe_name)
class Meta:
managed = True
unique_together = (('recipe_name', 'customer', 'ingredient'),)
我在食谱的管理中得到了一些奇怪的结果class...
from django.contrib import admin
from django.contrib.auth.models import User
from .models import RecipeControl
from Inventory import models
class RecipeView(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.active_by = request.user.username
obj.save()
fieldsets = [
('Recipe Information', {'fields': ['recipe_name', 'customer']}),
('Ingredients', {'fields': ['ingredient','min_weight','max_weight','active_recipe']}),
('Audit Trail', {'fields': ['active_by','revision','last_updated'],'classes':['collaspe']}),
]
list_select_related = ['recipe_name','customer','ingredient']
search_fields = ['recipe_name','customer','ingredient','active_by']
readonly_fields = ('last_updated','active_by')
list_display = ['recipe_name','customer','ingredient','min_weight','max_weight','last_updated','active_by', 'active_recipe']
admin.site.register(RecipeControl, RecipeView)
我遇到的问题是,如果我尝试在任何 ForeignKey 字段上进行搜索,Django 会抛出此错误...
Exception Type: TypeError at /admin/Recipe/recipecontrol/
Exception Value: Related Field got invalid lookup: icontains
根据 Django Admin Doc's 和其他有关 Whosebug 的旧问题,它说我应该按照 search_fields = ['inventoryitem__name' ] 但我认为这是对同一个应用程序中 FK 的引用 model.py。 是否有更正确的方法 referencing/importing 来自其他应用程序的其他模型,我丢失了,或者我是否必须使用某种可调用方法魔术来使搜索功能正确查找?我尝试了多种不同的组合,但似乎没有任何效果。我对 Django 比较陌生,所以我相信它很简单。
您应该使用双下划线符号来搜索相关对象的字段。但是,您应该使用外键字段的名称(例如 recipe_name
),而不是模型的名称(例如 InventoryItem
)。外键的模型是否在同一个应用程序中并不重要。例如:
search_fields = ['recipe_name__name']
请注意,如果您想搜索 recipe_name 和成分字段,您需要包括这两个字段,即使它们是同一模型的外键。
search_fields = ['recipe_name__name', 'ingredient__name']