简体   繁体   English

Django 通过多对多字段交集过滤对象

[英]Django filter objects by Many-To-Many field intersection

Hello,你好,

Can some good person give me advice on how to get a queryset of ordered objects by intersecting a many-to-many field with a given one object's many-to-many field?关于如何通过将多对多字段与给定一个对象的多对多字段相交来获得有序对象的查询集,一些好人可以给我建议吗?

For example I have:例如我有:

class Video(models.Model): class 视频(型号.型号):
tags = models.ManyToManyField(Tag, blank=True) tags = models.ManyToManyField(标签,空白=真)

... ...

class Tag(models.Model): class 标签(型号。型号):
name = models.CharField(max_length=64) 名称 = models.CharField(max_length=64)

... ...

I select one Video object and would like to have first ten objects that have most similar tags set to show like related videos.我 select 一个视频 object 并且希望将具有最相似标签的前十个对象设置为显示相关视频。

Thanks in advance!提前致谢!

I made a simple example, this should work我做了一个简单的例子,这应该有效

tag1 = Tag.objects.create(name="test video") #create a tag
video1 = Video.objects.create() #create a video
video1.tags.add(tag1) #add tag to video

video_query = Video.objects.filter(tags__name="test video")
print("query",video_query)

Now in this example its only 1 tag but if you have 100 tags put [:11] after video_query = Video.objects.filter(tags__name="test video")[:11]现在在这个例子中它只有 1 个标签但是如果你有 100 个标签把 [:11] 放在 video_query = Video.objects.filter(tags__name="test video")[:11] 之后

This will give you the exact match.这将为您提供精确匹配。

If you use:如果您使用:

 video_query = Video.objects.filter(tags__in=example_video.tags.all())

You will get a query with all the videos with at least 1 matching tag, if a video has 2 matching tags it will be present 2 times in the query.您将获得一个包含至少 1 个匹配标签的所有视频的查询,如果视频有 2 个匹配标签,它将在查询中出现 2 次。 You can fetch the videos which are present multiple times in the query.您可以获取查询中多次出现的视频。 You need to exclude example_video from the query您需要从查询中排除 example_video

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM