Q Lookups TypeError Django

时间:2017-03-29 13:23:26

标签: python django

在我的Car模型中,我有以下字段:name, manufacturer, body, car_type and description

我已经实现了一个搜索栏,但是当我搜索它时抱怨:

Related Field got invalid lookup: icontains

on Q(car_type__icontains=query)

这里究竟是什么问题?

query = request.GET.get("q")
if query:
    car = car.filter(
        Q(name__icontains=query) |
        Q(manufacturer__icontains=query) |
        Q(body__icontains=query) |
        Q(car_type__icontains=query)
    ).distinct()

Models.py

class CarModelBase(models.Model):

    class Meta:
        abstract = True
    name = models.CharField(max_length=100)

class CarType(CarModelBase, SortableModelBase):
    class Meta(CarModelBase.Meta):
        ordering = ['order']
        verbose_name = 'Car Type'
        verbose_name_plural = 'Car Types'

    def __str__(self):
        return self.name

class Car(CarModelBase):
    manufacturer = SortableForeignKey(Manufacturer)
    car_type = SortableForeignKey(CarType)
    body = SortableForeignKey(Body)
    description = models.TextField()

1 个答案:

答案 0 :(得分:2)

如果car_type是外键,则您无法Q(car_type__icontains=query)。您需要在CarTyoe模型上指定要搜索的字段,例如:

Q(car_type__name__icontains=query)