试图这样做:
wishList = WishList.objects.get(pk=20) matches = [val for val in Store.attribute_answers.all() if val in wishList.attribute_answers]
还有这个。
'ManyRelatedManager' object is not iterable
这两个字段都是多对多的,那么如何实现这一点呢?
听起来你是在找
Store.attribute_answers.all()
试试看
matches = [val for val in Store.attribute_answers.all() if val in WishList.attribute_answers.all()]
注意 WishList.attribute_answers.all()末尾的圆括号。添加圆括号会调用 all函数来返回一个迭代。
WishList.attribute_answers.all()
all
如果你加上括号,你就是在说“给我所有商店答案中的值,只要这个值也在愿望列表答案中”。如果没有括号,那么从商店的答案中要求所有值,这些值也包含在 all函数中,这是没有意义的。All 函数不是迭代函数(它是返回迭代函数的函数)
all()
对于每个人谁发现阅读问题代码作为 DR
而不是 query_set.many_to_many
query_set.many_to_many
你应该用 query_set.many_to_many.all()
query_set.many_to_many.all()
如果你是在一个模板中做到这一点:
{% for room in study.room_choice.all %} \{\{ room }} {% empty %} empty list! {% endfor %}
更新
如果您有一个 through 表,您可以像这样访问该表中的元素(详细的 给你)(注意,您使用的是 through 表名,小写为后缀 _ set) :
{% for roominfo in participant.roomchoicethru_set.all %} \{\{ roominfo.room}} \{\{ roominfo.telnumber}} {% endfor %}
这里的 busines _ type 是 profile 模型中的 foreign _ key
pro = Profile.object.filter(user=myuser).first() business_type = pro.business_type.all() if business_type: b_type = '' for b in business_type: b_type += str(b.type)+' ' a = b_type
每当这个问题出现的时候,我总是想到这个问题。特别是当尝试在函数中实际迭代多个函数时。
作为一个模板,你可以这样做:
array = many_to_many.all() for x in many_to_many: function here
答案是好的,我只是需要增加一点,更容易理解。您无法查询设置了 many to many 的字段,因为它返回并且对象不是选项列表。最好从视图中的字段获取数据,然后将其传递给模板。例如,如果您有帖子模型,其中每个帖子与标签模型有多对多的关系。
class Tag(models.Model): "" class Post(models.Model): tags = models.ManyToManyField(Tag)
如果您尝试 post.tag.caption,它将返回这个错误。
"post": identified_post, "post_tags":identified_post.tags.all()
而不是仅仅通过
"post": identified_post