Django 查询设置过滤器在 charfield 上反向启动

Django query set filter reverse startswith on charfield

图像某种具有 2 个条件的乘积规则:

规则模型如下所示:

class CreateAndAssignRule(models.Model):
    name_equals = models.CharField(max_length=100)
    sku_starts_with = models.CharField(max_length=100

现在我想获取名称为 Product 1 的所有规则并匹配 sku sku-b-292

class CreateAndAssignRuleQuerySet(QuerySet):
    def filter_by_name_and_sku(self, name, sku):
        # We're looking which of the rules have a matching name, and where the rule have a string which is the string of the sku provided.
        rules = self.filter(name_equals=name)

        approved_ids = []
        for rule in rules:
            # We're looping through the rules to find out which of them has the beginnings of the sku.
            # a sku_starts_with field would contains value eg: 'sku-a' where as the search string would be the full sku 'sku-a-111'.  We want to match 'sku-a-111' but not 'sku-b-222'.
            if sku.startswith(rule.sku_starts_with):
                approved.append(rule.id)

        return self.filter(id__in=approved_ids)

虽然上面的方法有效,但它几乎没有效率,尤其是当规则的数量开始大量增长时。

如何使用查询集解决这个问题?按 __startswith 过滤并不能解决问题,因为它恰恰相反。

过滤条件:

from django.db.models import <strong>F, Value</strong>

class CreateAndAssignRuleQuerySet(QuerySet):
    def filter_by_name_and_sku(self, name, sku):
        return self.alias(
            <strong>sku=Value(sku)</strong>
        ).filter(
            name_equals=name,
            <strong>sku__startswith=F('sku_starts_with')</strong>
        )

因此,我们在查询集中注入 sku,然后使用它来处理 __startswith lookup [Django-doc]