django - 针对不同用户的不同内联

时间:2016-11-20 23:23:35

标签: django inline

我有这些模型

class Office(models.Model):
    name = models.CharField(max_length=255)

class User(models.Model):
    name = models.CharField(max_length=255)
    status = models.SmallIntegerField()
    office = models.ForeignKey(Office, on_delete=models.SET_NULL, null=True)

class Inspection(models.Model):
    place = models.CharField(max_length=255, null=True, blank=True)

class Jobs(models.Model):
    inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE)
    inspector = models.ForeignKey(User, on_delete=models.SET_NULL)
    cost = models.DecimalField(max_digits=20, decimal_places=2)

我有不同的用户:普通用户(status=1)和管理员(status=2)。

普通用户只能通过同一办公室的Jobs制作并查看Inspectors

管理员可以将任何用户加入Inspectors并查看所有Jobs

我可以为同一办公室的用户过滤工作清单:

class JobAdmin(admin.StackedInline):
    model = Job
    extra = 0
    def get_queryset(self, request):
        qs = super(JobAdmin, self).get_queryset(request)
        if request.user.status in [1]:
            qs = qs.filter(inspector__office=request.user.office)
        return qs

 class InspectionAdmin(ModelAdmin):
    list_display = ['place']
    inlines = [JobAdmin]

但是如何添加其他过滤器进行编辑?

如果它不是内联形式,我会这样做:

class JobAdminForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(JobAdminForm, self).__init__(*args, **kwargs)

        if self.user.status == 1: #common user
            self.fields['inspector'].queryset = Inspector.objects.filter(office=self.user.office)

    class Meta:
        model = Jobs
        fields = '__all__'


class JobAdmin(ModelAdmin):
    form = JobAdminForm

    def get_form(self, request, obj=None, **kwargs):
        form = super(JobAdmin, self).get_form(request, **kwargs)
        form.user = request.user
        return form

1 个答案:

答案 0 :(得分:1)

也许这段代码会有所帮助:

class JobAdmin(admin.StackedInline):
    model = Job
    extra = 0

    def get_queryset(self, request):
        qs = super(JobAdmin, self).get_queryset(request)
        if request.user.status in [1]:
            qs = qs.filter(inspector__office=request.user.office)
        return qs

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == "inspector" and request.user.status == 1:
            kwargs['queryset'] = Inspector.objects.filter(office=request.user.office)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

P.S。链接到Django文档:formfield_for_foreignkey