没有ForeignKey异常Django

时间:2012-05-15 05:43:36

标签: django-models django-admin django-admin-filters

我们有这个模型,它有一个用户的外键:

class Medic(models.Model):
    user = models.ForeignKey(User)
    first_name = models.CharField(max_length=100, blank=True)
    middle_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)

在admin.py中,我们尝试将已在Medic页面上显示已注册的用户过滤为仅属于名为“staff”的组的用户:

from django.contrib import admin
from django.contrib.auth.models import User
from profiles.models import Medic

class StaffMed(admin.StackedInline):
    model = User
    def queryset(self, request):
        qs = super(StaffMed, self).queryset(request).filter(group__name='staff')
        return qs

class MedicAdmin(admin.ModelAdmin):
    inlines = [StaffMed]
    #model = Medic

admin.site.register(Medic, MedicAdmin)

然后我们得到这个例外:

class 'django.contrib.auth.models.User' has no foreignKey to class 'staff.models.Medic'

1 个答案:

答案 0 :(得分:0)

您必须指定具有外键的模型:

class StaffMed(admin.StackedInline):
    model = MedicAdmin

然后你需要像这样过滤:

    def queryset(self, request):
         qs = super(StaffMed, self).queryset(request).filter(user.group__name='staff')
         return qs