Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用django进行分组_Python_Django - Fatal编程技术网

Python 如何使用django进行分组

Python 如何使用django进行分组,python,django,Python,Django,我正在尝试使用Django进行分组 我有以下三种型号: class Tutorial(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) class Category(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=Fals

我正在尝试使用Django进行分组

我有以下三种型号:

class Tutorial(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)

class Category(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)
    tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, null=False)

class Video(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)
    tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, blank=False, null=False)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, blank=False, null=False)
@login_required
def player(request):
    tutorial_id = request.POST.get('id', None)
    videos = Video.objects.filter(tutorial=tutorial_id).values("name", "category__name")
在我看来,我有以下几点:

class Tutorial(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)

class Category(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)
    tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, null=False)

class Video(models.Model):
    name = models.CharField(max_length=200, unique=True, blank=False, null=False)
    tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, blank=False, null=False)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, blank=False, null=False)
@login_required
def player(request):
    tutorial_id = request.POST.get('id', None)
    videos = Video.objects.filter(tutorial=tutorial_id).values("name", "category__name")
视频
中,我得到:

[{'name': 'video1', 'category__name': 'category1'}, {'name': 'video2', 'category__name': 'category1'}, {'name': 'video4', 'category__name': 'category2'}]
但我想要的结果是:

[
{'category': 'category1', 'videos': [{'name': 'video1}, {'name': 'video2'}]},
{'category': 'category2', 'videos': [{'name': 'video4}]},
]
你知道怎么做吗?

也许会有帮助也许会有帮助