django admin使用mptt children

时间:2018-02-21 15:03:00

标签: django django-admin django-mptt

我试图弄清楚是否可以使用多个嵌套内联创建一个ModelAdmin,如:

  1. 合同
    • Mainproduct
      • Subproduct1
      • Subproduct2
        • SubSubproduct
  2. 我也试图用mpt来解决这些模型。 我的模型看起来像这样:

    class Contract(models.Model):    
        contractnumber =  models.CharField(max_length=25)
        field2 =  models.CharField(max_length=25)
        field3 =  models.CharField(max_length=25)
        field4 =  models.CharField(max_length=25)
    
        def __str__(self):
            return self.field1
    
        class Meta:
            verbose_name = 'Contract'
            verbose_name_plural = 'Contracts'
    
    class Mainproduct(MPTTModel):
        pr_c_contractnumber = models.ForeignKey(Contract)
        pr_name = models.Charfield(max_length=50)
        productdetails = models.Textfield(max_length=5000)
        pr_sernr = models.CharField(max_length=50)
        parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True,
                                on_delete=models.SET_NULL)
    
        def __str__(self):
            return self.pr_c_contractnumber, self.pr_name
    
        class MPTTMeta:
            order_insertation_by = ['pr_sernr']
    
        class Meta:
            verbose_name = 'Product'
            verbose_name_plural = 'Products'
    

    我的admin.py文件看起来像这样:

    class ProductModelInlineForm(forms.ModelForm):
        parent = TreeNodeChoiceField(queryset=Product.objects.all())
    
    class ProductModelInline(admin.TabularInline):
        model = Product
        form = ProductModelInlineForm
        extra = 1
    
    class ProductAdmin(admin.ModelAdmin):
        inlines = [ProductModelInline, ]
    
    class ProductInline(admin.TabularInline):
        model = Product
        extra = 1
    
    class ContractAdmin(admin.ModelAdmin):
        inlines = [ProductInline, ]
    

    有没有办法创建这些嵌套的内联?我错过了一些重要的事情吗?

1 个答案:

答案 0 :(得分:0)

只需使用under development feature即可自动执行此操作:

from mptt.admin import MPTTModelAdmin

admin.site.register(Mainproduct, MPTTModelAdmin)