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
非常感謝。它workds –
@MaslovAndrey在這種情況下,你可以記住我的答案作爲一個解決方案? –