问题
I have the following model.py. I want to create a filter during Input. SubCategory automatically extracted from members Category. While the input current during subcategory will display the entire contents without filter. I want to choose one parent, then just out of the parent's members only.
> from django.db import models
>
> > class Category(models.Model):
> > name = models.CharField(max_length=100)
> >
> > def __unicode__(self):
> > return self.name
> >
> > class SubCategory(models.Model):
> > name = models.CharField(max_length=50)
> > category = models.ForeignKey(Category)
> >
> > def __unicode__(self):
> > return self.name
> >
> > class Input(models.Model):
> > name = models.CharField(max_length=30)
> > category = models.ForeignKey(Category)
> > subcategory = models.ForeignKey(SubCategory)
> >
> > def __unicode__(self):
> > return self.name
回答1:
Have a look at the filter documentation.
To get a group of subcategories whose category field is populated by the category my_cat
, you would do -
sub_cats = SubCategory.objects.filter(category=my_cat)
来源:https://stackoverflow.com/questions/13775505/how-to-make-filter-query-in-django