Skip to main content
 首页 » 编程设计

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

2025年05月04日27pengyingh

我有两个相同类(模型)类型的对象。我想检查 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())