0

我正在尝试在存在通用外键的模型上进行管理员搜索。

管理员.py

class privacySettingsAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': (
                'field_name',
                'level',

            )
        }),
        (('page/article'), {
            'classes': ('grp-collapse grp-open',),
            'fields': ('content_type', 'object_id', )
        }),
    )
    autocomplete_lookup_fields = {
        'generic': [['content_type', 'object_id']],
    }
    search_fields = ('object_id',)

我可以使用搜索object_id。但我想使用该object_id对象的字段进行搜索。

前任。用户有一个外键来建模。然后我想使用usernamefirst_name和搜索该用户的隐私设置。emaillast_name

提前致谢。

4

1 回答 1

0

试试下面的代码:

在模型.py 中:

class PrivacySettings(models.Model):
    ...
    def object_username(self):
        return self.object.username
    object_username = property(object_username)

    def object_first_name(self):
        return self.object.first_name
    object_first_name = property(object_first_name)

    def object_last_name(self):
        return self.object.last_name
    object_last_name = property(object_last_name)

    def object_email(self):
        return self.object.email
    object_email = property(object_email)

在 admin.py 中:

class PrivacySettingsAdmin(admin.ModelAdmin):
    model = PrivacySettings
    fieldsets = (
        (None, {
            'fields': (
                'field_name',
                'level',

            )
        }),
        (('page/article'), {
            'classes': ('grp-collapse grp-open',),
            'fields': ('content_type', 'object_id', )
        }),
    )
    autocomplete_lookup_fields = {
        'generic': [['content_type', 'object_id']],
    }
    search_fields = ('object_id', 'object_username', 'object_first_name',
                     'object_last_name', 'object_email')
于 2015-08-03T09:32:27.817 回答