我正试图在我的主页中加入一个搜索域.它适用于某些模块字段.我的问题是当我使用ForeignKey字段时(如果我错了,请纠正我).

models.py

class Location(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    update_date = models.DateField(auto_now=True, null=True)

    def __str__(self):
        return self.my_location


class UserProfile(models.Model):

    user = models.ForeignKey(User)
    # The additional attributes we wish to include.
    user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    user_position = models.CharField(max_length=120)
    user_phone = models.PositiveIntegerField()

    def __unicode__(self):
        return self.user.username

views.py

def search_by_location(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        locations = Location.objects.filter(my_location__icontains=q).order_by('-update_date')
    else:
        locations = Location.objects.order_by('-update_date')
context = {'locations': locations}
return render(request, 'index.html', context)

我的问题是,如果我在过滤查询中使用user而不是my_location,我会收到错误:

相关字段的查找无效:图标

请提供有关如何排除故障的建议或我能阅读的任何文档.

推荐答案

您可以对文本字段使用icontains查找.user是相关(整数)字段.用user__username代替user.

locations = Location.objects.filter(user__username__icontains=q)

Django相关问答推荐

通过Model Form以编程方式设置Date TimeRangeField

Django中的Sync_to_Async修饰器、异步视图

无法在 docker 启动Django项目

如何在Django中显示文件大小

Django Admin:在一个部分中同时显示多个应用程序?

如果字段为空,则 Unique_together 不起作用.怎么约束呢?

Django prefetch_related 与 3 个不直接相关的模型

来自日历的 Django 动态 url

只从查询集中获取某种类型的最新项目

在Django Rest Framework中按模型属性排序时如何避免重新计算?

Django 在模型中存储用户图像

验证 Django 模型对象的正确方法?

在 django 中获取本地时区

在 Django 管理屏幕中删除添加另一个

Python/Django:从 values_list() 创建一个更简单的列表

导入错误无法在windows环境下导入名称execute_manager

模拟 Django 查询集以测试采用查询集的函数

从表单获取模型实例而不保存

如何以编程方式对 Django 中的用户进行身份验证?

在 Python 中生成 API KEY 和 SECRET 的最简单和最安全的方法是什么