Friday, September 14, 2012

django-mptt form queryset filtering

Let's assume that we have a model called Category which is a subclass of MPTTModel. And we'd like to display a product creation form where user would choose a category among the category tree.

To achieve this, we have to use     category = TreeForeignKey(Category) in the Product model. This allows us to display the choice as a hierarchical tree.

class Product(models.Model):
    name = models.CharField(max_length=50)
    category = TreeForeignKey(Category)

class ProductForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super (ProductForm,self ).__init__(*args,**kwargs)
        self.fields['category'].queryset = Category.tree.filter(site=kwargs['instance'].site_id)

    class Meta:
        model = Product

When you want to filter the categories according to some criteria, you should use Category.tree.filter, not the usual way: Category.objects.filter.

No comments: