2014-01-21 105 views
0

我想下拉列表關聯的材料和類別Django的表單對象過濾

車型

class Demande_Expertise(models.Model): 
    user = models.ForeignKey(User) 
    material = models.ForeignKey("Material") 
    categorie = models.ForeignKey("Category")  

class Category(models.Model): 
    name = models.CharField(_('name'), max_length=50) 
    slug = models.SlugField() 
    expert = models.ForeignKey(Expert, null=True, blank=True, default = None) 

class Material(models.Model): 
    name = models.CharField(_('name'), max_length=50) 
    description = models.TextField(_('description'), blank=True) 
    slug = models.SlugField() 
    category = models.ForeignKey(Category, verbose_name=_('category')) 

形式

class Demande_ExpertiseForm(forms.ModelForm): 
    class Meta: 
    model = Demande_Expertise 

def __init__(self, *args, **kwargs): 
    super(Demande_ExpertiseForm, self).__init__(*args, **kwargs) 
    self.fields['material'].queryset = Material.objects.filter(category=Category) 

沒有錯誤,但過濾不工作。

如何過濾name的型號Category

回答

0

您可以通過使用雙下劃線(在這種情況下爲category__name)過濾字段中查詢集中的關係,並傳入任何要過濾的關係。

class Demande_ExpertiseForm(forms.ModelForm): 
    class Meta: 
     model = Demande_Expertise 

    def __init__(self, *args, **kwargs): 
     super(Demande_ExpertiseForm, self).__init__(*args, **kwargs) 

     self.fields['material'].queryset = Material.objects.filter(category__name="name to filter") 

在這種情況下,它會過濾所有Material對象是那些有Category一套準確name to filter的。你可以通過閱讀the Django documentation on retrieving objects瞭解更多。