我有以下模型:

class Entity(models.Model):
       name=models.CharField(max_length=100)

class Theme(models.Model):
   name=models.CharField(max_length=100)
   entity=models.OneToOneField(Entity)

class Company(models.Model):
    name=models.CharField(max_length=100)
    theme=models.OneToOneField(Theme,null=True,blank=True)
我想在管理中添加theme时过滤Company字段,如下所示:
class CompanyAdmin(admin.ModelAdmin):
   def queryset(self, request):
      qs = super(CompanyAdmin, self).queryset(request)
      qs.theme.queryset = Theme.objects.filter(name__iexact='company')
      return qs

admin.site.register(Company, CompanyAdmin)
我已经尝试了很多东西,但是没有任何效果!我怎样才能做到这一点?

最佳答案

使用render_change_form方法:

class CompanyAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, *args, **kwargs):
         context['adminform'].form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
         return super(CompanyAdmin, self).render_change_form(request, context, *args, **kwargs)

关于python - 过滤Django管理中的foreignkey字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10179129/

10-12 17:59