Django ORM:注释匹配对象的值



我之前一直在使用 Django 的 ORM annotate,并成功了几次,但我在这个特定的情况下遇到了麻烦。

我想注释一个新字段,称为 tag_to_show ,当字段的值my_tag与某个正则表达式匹配时。

这是我目前所拥有的:

queryset.annotate(tag_to_show=Case(When(my_tag__iregex=pattern,
                                         then=Value("I don't know what to put here")),
                                    output_field=CharField(),
                                    default=Value("Not matched")))

我只是将正则表达式应用于my_tag字段。如果正则表达式与某个对象的my_tag字段中包含的字符串匹配,我想在一个名为 tag_to_show 的新字段中注释其值。

任何想法在 de Value参数中放入什么?

我认为你想要的是F() expression

queryset.annotate(tag_to_show=Case(
                      When(my_tag__iregex=pattern, then=F('my_tag')),
                      output_field=CharField(), 
                      default=Value("Not matched")))

我认为答案是:

queryset.annotate(tag_to_show=Case(When(my_tag__iregex=pattern,
               then='my_tag'),
               output_field=CharField(),
               default=Value("Not matched")))

最新更新