只允许叶类别作为选择 - Django

时间:2012-05-01 17:20:06

标签: django

我有以下型号:

class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    parent = models.ForeignKey('self', blank = True, null = True, related_name="children")

class Business(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    category = models.ForeignKey(Category)
    city = models.ForeignKey(City)

使用modelForm添加商家时,非叶子类别会显示在选择框中。

例如,假设我们有以下类别层次结构:

- Cars
     -- Car Rental
     -- Car Dealership
     -- Mechanics
- Restaurants
    -- Burgers
    -- Chinese
    -- Sushi
    -- Pizza
    -- Latin american
         -- Mexican
         -- Venezuelan
         -- Argentinian

使用此层次结构,除了“汽车”,“餐馆”和“拉丁美洲”之外的所有选项都应显示在“类别”选择框中,因为这些选项包含子类别。

1 个答案:

答案 0 :(得分:2)

Category.objects.filter(children__isnull=True)


class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].queryset = Category.objects.filter(children__isnull=True)