简体   繁体   English

如何在 Django 用户模型中搜索对象

[英]How to search for objects in the Django User model

I have a Profile model:我有一个配置文件模型:

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)
    ...

And a search contacts view:和搜索联系人视图:

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()

It is working fine but I would like to be able to search for contacts via the user field as well.它工作正常,但我也希望能够通过用户字段搜索联系人。 Does anyone know a way to do that?有谁知道这样做的方法吗?

EDIT my user's username's are created by them when they sign up to the site and are currently uneditable.编辑我的用户的用户名是他们在注册网站时创建的,目前无法编辑。 They are displayed on the admin page via a dropdown since they are a OneToOneField.它们通过下拉列表显示在管理页面上,因为它们是 OneToOneField。 I think my issue is that django recognises them only as an IntegerField('pk') but I need to somehow cast them as a string value.我认为我的问题是 django 仅将它们识别为 IntegerField('pk') 但我需要以某种方式将它们转换为字符串值。 Am I right in thinking that, and if so how can this be achieved?我的想法是否正确,如果是这样,如何实现? 在此处输入图片说明

You can add to your template to allow user to input user_username and save that username to q3:您可以添加到您的模板以允许用户输入 user_username 并将该用户名保存到 q3:

q3 = self.request.GET.get('user_username')

After that you can adjust your If condition accordingly, then change your return to something like:之后,您可以相应地调整您的 If 条件,然后将您的回报更改为:

Profile.objects.filter(Q(first_name__icontains=q1) |
                                          Q(last_name__icontains=q1),
                                          location__icontains=q2,
                                          user__username=q3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM