2016-11-20 50 views
0

我有這些模型Django的 - 不同的內聯針對不同的用戶

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

也許這個代碼將是有益的:

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) 

附:鏈接到Django文檔:formfield_for_foreignkey

+0

非常感謝。它workds –

+0

@MaslovAndrey在這種情況下,你可以記住我的答案作爲一個解決方案? –