“我的模型”设置为多对多关系,以将项目划分为组和类别:
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
您可以获得以下所有相关类别:
请注意
distinct()
的用法,因为它是一种m2m关系,您可以多次获取类别^{<在这种情况下,cd2>}将只返回唯一的类别相关问题 更多 >
编程相关推荐