【发布时间】:2020-11-03 05:54:40
【问题描述】:
我有一个 Profile 模型:
from django.contrib.auth.models import User
class Profile(models.Model):
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthday = models.DateField(null=True, blank=True)
bio = models.TextField(blank=True, max_length=1000)
location = models.CharField(max_length=100, blank=True)
...
还有一个搜索联系人视图:
class SearchContactsView(ListView):
model = Profile
template_name = 'users/contact_search.html'
context_object_name = 'qs'
def get_queryset(self):
q1 = self.request.GET.get('contact_name')
q2 = self.request.GET.get('contact_location')
if q1 or q2:
return Profile.objects.filter(Q(first_name__icontains=q1) |
Q(last_name__icontains=q1),
location__icontains=q2)
return Profile.objects.all()
它工作正常,但我也希望能够通过用户字段搜索联系人。有谁知道这样做的方法吗?
编辑我的用户的用户名是他们在注册网站时创建的,目前不可编辑。它们通过下拉菜单显示在管理页面上,因为它们是 OneToOneField。我认为我的问题是 django 仅将它们识别为 IntegerField('pk') 但我需要以某种方式将它们转换为字符串值。我的想法对吗?如果是这样,如何实现?
【问题讨论】:
标签: django search django-users