如何在Django queryset中过滤ManyToMany字段?

jyztefdp  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(131)

我有模型:

class VideoParameter(models.Model):
    member = models.ForeignKey(Tag, on_delete=models.DO_NOTHING, related_name="parameter_tag")
    value = models.PositiveIntegerField()

class Video(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    parameters = models.ManyToManyField(VideoParameter, related_name="video_parameter")
    url = models.URLField(verbose_name=_('Url'))

字符串
(我的意思是,视频有一些参数,如键值(例如{“兔子”:1,“Pandas”:1,“狮子”:0}))
然后,我试图获得视频,由查询参数指定。
(like此/video/?rabbit=1&panda=1&lion=0
我想做的SQL代码如下:

SELECT app_video.id, count(*) AS match_count FROM app_video 
INNER JOIN app_video_parameters on app_video.id = app_video_parameters.video_id
INNER JOIN app_videoparameter ON app_video_parameters.videoparameter_id = app_videoparameter.id 
WHERE (app_videoparameter.member_id = 1 AND app_videoparameter.value = 0) 
OR (app_videoparameter.member_id = 9 AND app_videoparameter.value = 1)
OR (app_videoparameter.member_id = 11 AND app_videoparameter.value = 1)
...
GROUP BY (app_video.id) 
ORDER BY match_count DESC;


如何在Django queryset中实现这个过程?

7vhp5slm

7vhp5slm1#

你可以先构造一个Q对象:

from django.db.models import Count, Q

data = {'rabbit': 1, 'panda': 1, 'lion': 0}
q = Q(
    *[
        Q(parameters__member__name=k, parameters__value=v)
        for k, v in data.items()
    ],
    _connector=Q.OR
)
Video.objects.filter(q).annotate(
    match_count=Count('parameters')
).order_by('-match_count')

字符串

相关问题