django python中的Search_fields

时间:2010-01-21 00:21:13

标签: python django-admin

我想知道如何使用外键来执行搜索示例

class Product(models.Model):
    name = models.CharField(max_length = 127)
    description = models.TextField()
    code = models.CharField(max_length = 127)

    def __unicode__(self):
        return self.name + " - " + self.code

class ProductLot(models.Model):
    product = models.ForeignKey(Product)
    code = models.CharField(max_length = 30)
    lot_no = models.CharField(max_length = 30)
    location = models.CharField(max_length = 127)
    incoming = models.IntegerField()
    commited = models.IntegerField()
    available = models.IntegerField()
    reorder = models.IntegerField()
    created_date = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return self.code + " - " + self.product.name + " - " + self.lot_no

class LotComment(models.Model):
     product_lot = models.ForeignKey(ProductLot)
     comment_user = models.ForeignKey(User, null=True)
     comment_text = models.TextField()
     created_date = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return self.product_lot.product.code + " - " + 
           self.product_lot.product.name + " - " + 
           self.product_lot.lot_no + " - " + str(self.created_date)

比我的admin.py文件

from CMS.Inventory.models import Product

class padmin(admin.ModelAdmin):
    search_fields=['name', 'description', 'code', 'lot_no' ]
admin.site.register(Product, padmin)

但我希望“LotComments”能够使用“产品”可以与代码等相同的搜索字段。

希望我能解释清楚

3 个答案:

答案 0 :(得分:16)

您可以在admin search_fields中指定相关的字段搜索,就像在Django查询集上一样。检查documentation。对于LotComments对象,search_fields看起来像:

search_fields = ['product_lot__product__name', 
                 'product_lot__product__description', 
                 'product_lot__product__code',
                 'product_lot__lot_no']

答案 1 :(得分:2)

添加到之前的答案。我想建议Django Admin advance filters

使用此插件添加高级搜索并保存高级搜索支持。 在您的情况下,外键字段也可以映射到名称。

class padmin(AdminAdvancedFiltersMixin, admin.ModelAdmin):
    advanced_filter_fields = ('name', ('product_lot__product__name', 'Product name'))

答案 2 :(得分:1)

用于引用外键使用__(两个下划线):

from CMS.Inventory.models import Product

class ProductAdmin(admin.ModelAdmin):
    search_fields=['name__name', 'description', 'code', 'lot_no' ]
    admin.site.register(Product, padmin)