如何使用扩展模型字段对管理员中的django用户进行排序

时间:2014-07-16 20:33:42

标签: django django-admin

嗨所以我扩展了我的用户类:

class InsiderUser(models.Model):
    user = models.OneToOneField(User)
    apartment = models.BooleanField()
    retail = models.BooleanField()
    land = models.BooleanField()
    offshop = models.BooleanField()
    industrial = models.BooleanField()
    reportcount = models.IntegerField(null=True, blank=True, default=0)
    company_name = models.CharField(max_length=100L, blank=True)
    company_street = models.CharField(max_length=100L, blank=True)
    company_city = models.CharField(max_length=100L, blank=True)
    company_state = models.CharField(max_length=2L, blank=True)
    company_zip = models.IntegerField(max_length=10L, null=True, blank=True)
    company_number = models.CharField(max_length=10L, null=True, blank=True)

要在django admin dashboard中显示我已完成的company_name字段:

class UserAdmin(UserAdmin):
    inlines = (InsiderUserInline, )
    list_display = ('username', 'display_company_name', 'email', 'first_name', 'last_name')

    #below shows extended fields in admin user table
        def display_company_name(self, request):
            if InsiderUser.objects.filter(user__id = request.id):
                return InsiderUser.objects.get(user__id = request.id).company_name
            else:
                return None
        display_company_name.short_description = 'Company Name'

    # Re-register UserAdmin
    admin.site.unregister(User)
    admin.site.register(User, UserAdmin)

我试过了

def display_company_name(self, request):
    if InsiderUser.objects.filter(user__id = request.id):
        return InsiderUser.objects.get(user__id = request.id).company_name
    else:
        return None
display_company_name.short_description = 'Company Name'
display_company_name.admin_order_field = 'insider_user__company_name'

虽然它确实使表头可以点击,但它给了我以下错误:

Cannot resolve keyword u'insider_user' into field. Choices are: date_joined, email, first_name, groups, id, insideruser, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions, username

1 个答案:

答案 0 :(得分:2)

Cannot resolve keyword u'insider_user' into field. Choices are: date_joined, email, first_name, groups, id, insideruser, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions, username

看到这个,我会说你可以尝试用以下代替:

display_company_name.admin_order_field = 'insideruser__company_name'#insideruser, not insider_user