You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中按所属用户过滤联系人?求实现方案

问题解答

必须通过contact_belongs_to字段进行过滤,否则查询会返回系统中所有用户的联系人,无法实现仅展示当前登录用户自有联系人的需求。以下是具体实现方案:

1. 确保用户登录权限

无论使用函数视图还是类视图,都需要先限制仅登录用户可访问联系人列表:

  • 函数视图:使用@login_required装饰器
  • 类视图:继承LoginRequiredMixin

2. 过滤当前用户的联系人查询集

函数视图实现

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Contact

@login_required
def contact_list(request):
    # 过滤出属于当前登录用户的联系人
    user_contacts = Contact.objects.filter(contact_belongs_to=request.user)
    return render(request, 'contacts/contact_list.html', {'contacts': user_contacts})

类视图(ListView)实现

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
from .models import Contact

class ContactListView(LoginRequiredMixin, ListView):
    model = Contact
    template_name = 'contacts/contact_list.html'
    context_object_name = 'contacts'

    def get_queryset(self):
        # 重写查询集,仅返回当前用户的联系人
        return super().get_queryset().filter(contact_belongs_to=self.request.user)

3. 模板渲染联系人列表

在contacts/contact_list.html中渲染过滤后的联系人:

<h1>我的联系人</h1>
<ul>
    {% for contact in contacts %}
        <li>
            <strong>{{ contact.name }} {{ contact.surname }}</strong>
            <p>电话: {{ contact.phone_number }}</p>
            {% if contact.email %}<p>邮箱: {{ contact.email }}</p>{% endif %}
        </li>
    {% empty %}
        <li>暂无联系人,快去添加吧</li>
    {% endfor %}
</ul>

优化联系人创建代码

你当前的post方法可以简化,避免手动传递所有字段:

def post(self, request: HttpRequest) -> HttpResponse:
    # 上传图片需要传入request.FILES
    form = ContactForm(request.POST, request.FILES)
    if form.is_valid():
        # 先不提交到数据库,关联用户后再保存
        contact = form.save(commit=False)
        contact.contact_belongs_to = request.user
        contact.save()
        return HttpResponse('OK')
    else:
        return render(request, 'contacts/contact_form.html', context={'form': form})

内容的提问来源于stack exchange,提问作者INZAGHI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 11:47:27