是否可以基于__str__查询数据库?

时间:2019-08-18 13:34:27

标签: python django django-models

从理论上说,我有以下三种模型:


    class Cable(models.Model):
        id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE)
        type = models.IntegerField(choices=choices.cableTypes, default=1)
        notes = models.TextField(blank=True)
        length = models.DecimalField(decimal_places=2, max_digits=6)

        def __str__(self):
            return str(self.get_type_display()) + " Cable, " + str(self.length) + "m"


    class Adapter(models.Model):
        id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE)
        adaptFrom = models.IntegerField(choices=choices.connectors, default=1)
        adaptTo = models.IntegerField(choices=choices.connectors, default=1)
        notes = models.TextField(blank=True)
        length = models.DecimalField(decimal_places=2, max_digits=6)

        def __str__(self):
            return str(self.get_adaptFrom_display()) + " to " + str(self.get_adaptTo_display())


    class Fixture(models.Model):
        id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE)
        type = models.IntegerField(choices=choices.fixtureTypes, default=1)
        model = models.CharField(blank=False, max_length=128)
        manufacturer = models.CharField(blank=False, max_length=128)
        notes = models.TextField(blank=True)

        def __str__(self):
            return str(self.manufacturer) + " " + str(self.model)

是否可以根据它们返回的字符串来查询这些模型?如果没有,我将如何做类似的事情?

之所以需要这样做,是因为我有一个名为item的父模型(所有这些模型都是从那里获取其主键的),但是我仍然需要对我的网站实施搜索功能。

这是我目前的做法,这有点混乱:

    results = []
        form = SearchForm(request.POST)
        if form.is_valid():
            for category in Type.objects.all():
                for item in Item.objects.all():
                    if item.type == category:
                        model = apps.get_model("dashboard", model_name=category.name.lower())
                        itemreferenced = model.objects.get(id=item.id)
                        if form.cleaned_data["query"] in str(itemreferenced).lower():
                            results.append(itemreferenced)
        context["searchResults"] = results

1 个答案:

答案 0 :(得分:2)

您可以.annotate()合并多个字段的查询,然后在该新字段上.filter()

from django.db.models import CharField, Value
from django.db.models.functions import Concat

Cable.objects.annotate(
    description=Concat(
        'type', Value(" Cable, "), 'length', Value("m"),
        output_field=CharField()
    ).filter(
       description__icontains=query
    )
)