本文介绍了获取存储在多对多字段中的所有唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多对多的字段称为类别
,我想得到存储在该字段中的不同值。
I have a many-to-many field called categories
and I would like to get distinct values stored in that field.
以下是我的模型:
class Book (models.Model):
categories=models.ManyToManyField(Category, related_name = 'categories', blank = True, null=True)
我的类别模型:
class Category (MPTTModel):
category = models.CharField(max_length=250)
parent = TreeForeignKey('self', blank=True, null=True, related_name='children')
我想获得与一本书相关的每一个类别。我如何做到这一点?
I'd like to get every single one of the categories related to a book. How would I do this?
推荐答案
如果你想获得与一个 ,do book_inst.category_set.all()
。不会有重复。
If you want to get categories related to one instance of book, do book_inst.category_set.all()
. There will not be duplicates.
但我想,你想要得到所有与相关的类别
>任何 书
,您可以:
But I think, you want to get all Categories
which are related to any Book
, you can do:
Category.objects.filter(categories__in=[Book.objects.all()]).distinct()
这篇关于获取存储在多对多字段中的所有唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!