1

我有以下型号:

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

使用此层次结构,除汽车、餐厅和拉丁美洲之外的所有选项都应显示在类别选择框中,因为它们具有子类别。

4

1 回答 1

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)
于 2012-05-01T17:28:21.323 回答