-1

I have the following model:

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)

And this view:

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")

Everything works as expected.
Now I want to filter videos through categories. How can I construct a query like:
"Give me all the 'Videos', which have an entry in 'VideoCategory' with the 'Category'.name like 'xxxxxxx'"

4

1 回答 1

1

你可以做:

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

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

您可以在此处阅读如何查询跨越关系的查找

于 2013-08-28T21:01:35.233 回答