django中的三向查询

时间:2013-08-28 20:59:23

标签: django

我有以下型号:

class Video(models.Model):
    name = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    filename = models.CharField(max_length=200)
    duration = models.IntegerField(default=0)
    votes_up = models.IntegerField(default=0)
    votes_down = models.IntegerField(default=0)
    width = models.IntegerField(default=0)
    height = models.IntegerField(default=0)

    def __unicode__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

class VideoCategory(models.Model):
    video = models.ForeignKey('Video')
    category = models.ForeignKey('Category')

    def __unicode__(self):
        return u"{} >> {}".format(self.video.name, self.category.name)

这个观点:

def video_list(request):
    if 'category' in request.POST:
        #####
    else:
        video_list = Video.objects.order_by('pub_date')

    context = {}
    context['videos'] = []
    for video in video_list:
        video_data = {'name': video.name,
                      'file': video.filename,
                      'duration': video.duration,
                      'resolution': [video.width, video.height],
                     }
        context['videos'].append(video_data)
    return HttpResponse(json.dumps(context), content_type="application/json")

一切都按预期工作 现在我想通过类别过滤视频。如何构造如下的查询:
“给我所有的'视频',在'VideoCategory'中有一个条目,'Category'.name就像'xxxxxxx'”

1 个答案:

答案 0 :(得分:1)

你可以这样做:

videos = Video.objects.filter(videocategory__category__name='xxxx')

(注意小写模型名称以访问反向关系)

您可以阅读如何查询lookups that span relationships here