python - 在 Django 中检查 M2M 交叉点的有效方法?

标签 python django

我有两个相同类(模型)类型的对象。我想检查 M2M 字段上的交叉点。有没有一种不使用原始 SQL 的有效方法来执行此操作?

基本上,这是我当前的解决方案。

genres_a = [g for g in profile_a.genres.all()] # Convert to List
genres_b = set([g for g in profile_b.genres.all()]) # Convert to Set

if genres_b.intersection(genres_a): # Look for Intersection (Not Lazy)
    print True # Do something...

最佳答案

如果我正确理解交集:

profile_a.genres.all().filter(id__in=profile_b.genres.all())

关于python - 在 Django 中检查 M2M 交叉点的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9807500/

相关文章:

python - 装饰 @property 并接受参数的装饰器

django - 'ManyToManyDescriptor'对象在django 2中没有属性'all'

python - Django 1.5 包含的 urlconf 中没有任何模式

python - 记录更改列表中的 Django-admin : How to display link to object info page instead of edit form ,?

django - 用Count注释无法正常工作

python - 如何在图形/绘图(在 matplotlib 中)上显示对象的值?

python - 如何解决 xml.etree.ElementTree.iterparse() 中的 Unicode 错误?

python - 如何将 Matplotlib 的 stock_img() 与 Cartopy 的 NearsidePerspective 投影相匹配

python - 如何处理类层次结构中的Python装饰器?

python - Django 让用户通过表单更新网站上的 TextField 值?