确定通过多个关系链接的“可到达”对象

2024-09-30 01:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

“我的模型”设置为多对多关系,以将项目划分为组和类别:

class DownloadableResourceGroup(models.Model):
    pass

class DownloadableResourceCategory(models.Model):
    pass

class DownloadableResource(models.Model):    
    res_categories = models.ManyToManyField(DownloadableResourceCategory, blank=True)
    res_groups     = models.ManyToManyField(DownloadableResourceGroup, blank=True

每个视图都有一个分配给它的资源组,它提供了资源的初始筛选。然后,我想根据类别应用进一步的过滤器。我的问题是-如何从由DownloadableResourceGroup过滤的DownloadableResources中获取DownloadableResourceCategories列表而不进行迭代?我只想显示DownloadableResources上当前视图中的类别,不想显示其中没有任何项目的类别

为了进一步说明我在做什么:

# fetch relevant DownloadableResources
items = active_collection.downloadableresource_set.all().order_by("title")

# get only categories present in the items above
relevant_categories = THIS_IS_WHAT_I_AM_AFTER

Tags: 项目视图truemodelmodelsrespass类别

热门问题