簡體   English   中英

使用 Django 的 Case/When 查詢集條件訪問行的值

[英]Access value of row using Django's Case/When queryset conditions

我正在嘗試遷移 Django 中的一些值,我使用的是 Django 模型的When-Case 我的實現很簡單,它使用 static 字符串:

When(
            description__in=pre_desc,
            then=Value("pre-string"),
        ),
        When(
            description__in=post_desc,
            then=Value("some-post-string"),
        )

上面的代碼有效。 但是當我嘗試在現有字符串之前或之后添加一些內容時,問題就出現了:

pre_desc = ["a", "b", "c"]
post_desc = ["a", "b", "c"]


StoreO.objects.filter().update(
    description=Case(
        When(
            description__in=pre_desc,
            then=Value("pre-string"+description),
        ),
        When(
            description__in=post_desc,
            then=Value(description+"some-post-string"),
        ),
        default=Value("def_str")),
    )
)

它說, description未定義。 誰能給我一些解決方法?

我還嘗試了str(F('description')+'randomstr')導致數據庫中出現F('description')+'randomstr'

您使用F表達式[Django-doc]引用字段,或者在此處使用Concat [Django-doc]連接字符串:

from django.db.models.functions import Concat

pre_desc = ['a', 'b', 'c']
post_desc = ['a', 'b', 'c']

StoreO.objects.all().update(
    description=Case(
        When(
            description__in=pre_desc,
            then=Concat(Value('pre-string'), 'description'),
        ),
        When(
            description__in=post_desc,
            then=Concat('description', Value('some-post-string')),
        ),
        default=Value('def_str')),
    )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM