正确使用search_fields中的外键引用,Django admin

时间:2016-02-01 11:50:37

标签: django django-admin django-admin-tools django-modeladmin

我有一个奇怪的难题,我需要在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'),)

我在Recipe的Admin课程中得到了一些奇怪的结果......

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以及有关该主题的stackoverflow的其他旧问题,它说我应该按照 search_fields = [' inventoryitem__name'] 的方式做一些事情。但我认为这是在同一个应用程序model.py中引用FK的。 有没有更正确的方法从我缺少的其他应用程序中引用/导入其他模型,或者我必须使用某种可调用方法魔法来使搜索功能正确查找?我尝试过多种不同的组合,但似乎没有任何效果。我对Django来说相对较新,所以我确信它很简单。

1 个答案:

答案 0 :(得分:4)

您应该使用双下划线表示法来搜索相关对象上的字段。但是,您应该使用外键字段的名称(例如recipe_name),而不是模型的名称(例如InventoryItem)。外键的模型是否在同一个应用程序中并不重要。例如:

search_fields = ['recipe_name__name']

请注意,如果要搜索recipe_name和recipe字段,则需要包含这两个字段,即使它们是同一模型的外键。

search_fields = ['recipe_name__name', 'ingredient__name']