如何在django管理页面中过滤当前用户的foriegnkey对象

时间:2017-06-10 22:08:31

标签: django django-models

这是ClassAdmin类:

class CategoryAdmin(admin.ModelAdmin):
    list_display = ['name','desc','text']
    fieldsets = [(None, {'fields': ['name', 'desc', 'text']}),]

    def save_model(self, request, obj, form, change):
        if not obj.id:
            obj.user = request.user
            obj.save()

    def get_queryset(self, request):
        qs = super(CategoryAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

模型类产品:

class Product(models.Model):
    user = models.ForeignKey("auth.User", db_index=True)
    name = models.CharField(max_length=64)
    text = models.CharField(max_length=512)
    pub_dt = models.DateTimeField('date published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.")
    cate = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)

模型类别:

 class Category(models.Model):
     user = models.ForeignKey("auth.User", db_index=True)
     name = models.CharField(max_length=64)
     desc = models.CharField(max_length=128)
     text = models.CharField(max_length=512)

     def __str__(self):
         return self.name

当我添加产品时,cate字段是下拉列表。如何在ModelAdmin的子类中按当前用户过滤类别下拉列表中的项目。

1 个答案:

答案 0 :(得分:0)

您可以使用formfield_for_foreignkeysource)。

在您的情况下,就像这样:

class ProductAdmin(admin.ModelAdmin):
    list_display = ['name','category']
    fieldsets = [(None, {'fields': ['name', 'category']}),]

def save_model(self, request, obj, form, change):
    ...

def get_queryset(self, request):
    ...

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "category":
        kwargs["queryset"] = Category.objects.filter(user=request.user)
    return super().formfield_for_foreignkey(db_field, request, **kwargs)