【问题标题】:Search field on generic foreign key field通用外键字段上的搜索字段
【发布时间】:2019-04-17 11:13:22
【问题描述】:

我正在尝试向 Django 管理模型 CreditsAdmin 添加一个搜索字段,这将允许我搜索相关客户对象的电子邮件。 Customer 对象具有许多不同类型对象的通用外键,所有这些对象都有电子邮件。

我已经尝试在 Customer 对象上定义函数 customer_email 并将其用作搜索字段,但这会产生错误 Related Field got invalid lookup: customer_email

class Customer(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    @property
    def customer_email(self):
        return str(self.content_object.email)


class Credits(models.Model):
    credits_remaining = models.IntegerField()
    current_period_start = models.DateTimeField()
    current_period_end = models.DateTimeField()
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)


class CreditsAdmin(admin.ModelAdmin):
    list_display = (
        'current_period_start',
        'current_period_end',
        'customer_name',
        'credits_remaining',
    )

    search_fields = ('customer__customer_email',)

我希望能够从CreditsAdmin 接口搜索Customer 模型上相关通用对象的电子邮件。特别是,与客户对象相关的 content_type 之一是 django 的 auth.User 模型,但还有其他的。

【问题讨论】:

    标签: django django-models django-admin


    【解决方案1】:

    您不能在 search_fields 中使用属性,因为它会在数据库级别查找列。

    GenericRelation 可能是一个解决方案。您可以在相关(按内容类型)模型中创建字段。例如:

    class CntObject(models.Model):
        customers = GenericRelation(Customer, related_query_name='cnt_objects')
    

    在积分管理面板中:

    class CreditsAdmin(admin.ModelAdmin):
    list_display = (
        'current_period_start',
        'current_period_end',
        'customer_name',
        'credits_remaining',
    )
    
    search_fields = ('customer__cnt_objects__email',)
    

    这个答案并不是最好的。您必须确保所有相关的 content_objects 都有 email 字段。可能是性能问题,没有测试。

    其他解决方案可能是您在管理类中的自定义 get_search_results 方法。

    【讨论】:

    • 由于我是直接使用django User模型,所以无法添加GenericRelation。覆盖 get_search_results 是要走的路
    • @unstarreren8271 介意与 get_search_results 分享您的解决方案吗?
    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2014-01-04
    相关资源
    最近更新 更多