简体   繁体   中英

How do I filter this in Django ORM

Here is my models.py

class Category(models.Model):
    name = models.CharField(max_length=200, default='')
    slug = models.SlugField(max_length=100,default='',unique=True)

    def __unicode__(self):
        return self.name


class SubCategory(models.Model):
    category = models.ForeignKey(Category)
    name = models.CharField(max_length=200, default='')
    slug = models.SlugField(max_length=100,default='',unique=True)


class TutorInfo(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=255, default='')
    category = models.ManyToManyField(Category, related_name='categories')
    about = models.TextField(default='')


class Course(models.Model):
    user = models.ForeignKey(User)
    category = models.ForeignKey(Category)
    sub_category = models.ForeignKey(SubCategory)
    course_name = models.CharField(max_length=255, default='')

Now I want to filter the TutorInfo such that sub_category matches the sub_category in their added Course . A Tutor can have more than one Course . Is it possible to write such a query? If not then please advice me what alterations should I do in the models.py

If 1 is the id of the sub_category you're interested in, use

TutorInfo.objects.filter(user__course__sub_category__id__exact=1)

whether if sc is the sub_category model instance:

TutorInfo.objects.filter(user__course__sub_category=sc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM