django admin site查看一对一的类字段

时间:2013-05-14 09:43:44

标签: python django django-admin

在我的模特中:

class Professor(models.Model):
  user = models.OneToOneField(User)
  salary = models.FloatField()
class Student(models.Model):
  user = models.OneToOneField(User)
  birth_date = models.DateField()

在我的admin.py

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

UserAdmin.list_display = ('email', 'first_name', 'last_name','is_active','date_joined', 'is_staff')

如果用户是教授或学生,我如何在用户管理站点内显示?是否可以访问基于模型个人的工资等属性。

2 个答案:

答案 0 :(得分:2)

您可以在list_display中使用自定义方法。这是代码:

from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.contrib.auth.models import User

class UserAdmin(DjangoUserAdmin):
    list_display = ('email', 'first_name', 'last_name','is_active','date_joined', 'is_staff', 'user_type', 'salary')

    def user_type(self, instance):
        try:
            instance.student
            return "student"
        except Student.DoesNotExist:
            return "professor"

    def salary(self, instance):
        try:
            return instance.professor.salary
        except Professor.DoesNotExist:
            return "N/A"

    def queryset(self, request):
        qs = super(UserAdmin, self).queryset(request)
        # To reduce database calls
        return qs.select_related('student', 'professor')


admin.site.unregister(User)
admin.site.register(User, UserAdmin)

它会向change_list管理页面添加其他列user_typesalary

<强>已更新: 感谢@Adrián López。现在从django内置UserAdmin继承。

答案 1 :(得分:1)

您可以使用inline

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class ProfessorInline(admin.StackedInline):
    model = Professor

class StudentInline(admin.StackedInline):
    model = Student

class MyUserAdmin(UserAdmin):
    inlines = [ProfessorInline, StudentInline]


admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)

这不完美。它应该在User管理面板中显示ProfessorStudent字段。它不会明确说明是Professor还是Student。说实话,这并没有多大意义,你没有使用此处,所以在技术上你可能有User同时是ProfesssorStudent同时。

如果您更喜欢,也可以尝试TabularInline