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

如何在Django票务系统中过滤模型获取激活PIN的宾客信息?

Django票务应用:PIN激活状态检查及宾客资料获取实现方案

问题描述

我正在开发一个Django票务应用,其中设有PIN状态检查视图。需求为:查询Pin模型判断PIN是否已激活,若已激活则查询Guest和Profile模型获取宾客资料信息并在模板中展示。目前我已能通过Django表单结合搜索功能展示PIN详情,但无法实现PIN激活时获取宾客资料的逻辑代码,恳请提供帮助。

现有模型代码

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
    surname = models.CharField(max_length=20, null=True)
    othernames = models.CharField(max_length=40, null=True)
    gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
    phone = PhoneNumberField()
    image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images')

    # 保存时调整图片尺寸
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img = Image.open(self.image.path)
        if img.height > 200 or img.width > 150:
            output_size = (150, 250)
            img.thumbnail(output_size)
            img.save(self.image.path)

    def __str__(self):
        return f'{self.user.username}-Profile'

class Pin(models.Model):
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
    value = models.CharField(max_length=6, default=generate_pin, blank=True)
    added = models.DateTimeField(auto_now_add=True,  blank=False)
    reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
    status = models.CharField(max_length=30, default='Not Activated')

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs) 

    def __unicode__(self):
        return self.ticket

    class Meta:
        unique_together = ["ticket", "value"]

    def __str__(self):
        return f"{self.ticket}"

    def get_absolute_url(self):
        return reverse("pin-detail", args=[str(self.id)])

class Guest(models.Model):
    guest_name = models.CharField(max_length=30, null=True)
    pin = models.CharField(max_length=6, null=True)

    def __str__(self):
        return f"{self.guest_name}" 

现有视图代码

def Pin_Searcht(request):
    context = {}
    #Search PIN Form
    searchForm = SearchEventTicketForm(request.GET or None)

    if searchForm.is_valid():
        #Value of search form
        value = searchForm.cleaned_data['value']
        user_pin = Pin.objects.filter(value=value)
    else:
        user_pin = Pin.objects.order_by('-added')[:2]
      
    page_title = "Search and Print PINs"
    context.update ({
        'page_title':page_title,
        'list_pins':paged_listPin,
        'searchForm':searchForm,
        'page_title':"PIN Status",
    })
    return render(request, 'user/pin_list.html', context)

解决方案

1. 修复并完善视图逻辑

先修正原视图中未定义变量、重复赋值等问题,再添加激活状态判断与宾客资料查询逻辑:

def Pin_Searcht(request):
    context = {}
    searchForm = SearchEventTicketForm(request.GET or None)
    # 初始化资料变量
    guest_info = None
    profile_info = None
    user_pin = None

    if searchForm.is_valid():
        value = searchForm.cleaned_data['value']
        # 用get()替代filter(),因为PIN值唯一(模型已设置unique_together)
        try:
            user_pin = Pin.objects.get(value=value)
            # 判断PIN是否激活
            if user_pin.status == 'Activated':
                # 查询对应宾客
                try:
                    guest_info = Guest.objects.get(pin=value)
                    # 通过宾客姓名关联Profile(可根据实际业务调整匹配逻辑)
                    try:
                        user = User.objects.get(username=guest_info.guest_name)
                        profile_info = Profile.objects.get(user=user)
                    except (User.DoesNotExist, Profile.DoesNotExist):
                        profile_info = None
                except Guest.DoesNotExist:
                    guest_info = None
        except Pin.DoesNotExist:
            user_pin = None
    else:
        user_pin = Pin.objects.order_by('-added')[:2]

    context.update({
        'page_title': "PIN Status",
        'user_pin': user_pin,
        'searchForm': searchForm,
        'guest_info': guest_info,
        'profile_info': profile_info
    })
    return render(request, 'user/pin_list.html', context)

2. 优化模型关联(推荐)

原模型中Guest与Pin通过字符串关联易出错,建议改为外键关联:

class Guest(models.Model):
    guest_name = models.CharField(max_length=30, null=True)
    pin = models.ForeignKey(Pin, on_delete=models.CASCADE, null=True, related_name='guests')

    def __str__(self):
        return f"{self.guest_name}" 

修改后视图中查询宾客可简化为:

guest_info = Guest.objects.get(pin=user_pin)

3. 模板中展示数据

在pin_list.html中添加条件渲染逻辑:

{% if user_pin %}
    <h3>PIN状态:{{ user_pin.status }}</h3>
    {% if user_pin.status == 'Activated' %}
        {% if guest_info %}
            <h4>宾客信息</h4>
            <p>姓名:{{ guest_info.guest_name }}</p>
            {% if profile_info %}
                <h4>详细资料</h4>
                <p>姓氏:{{ profile_info.surname }}</p>
                <p>名字:{{ profile_info.othernames }}</p>
                <p>性别:{{ profile_info.gender }}</p>
                <p>电话:{{ profile_info.phone }}</p>
                <img src="{{ profile_info.image.url }}" alt="头像" width="150" height="250">
            {% else %}
                <p>暂无详细资料</p>
            {% endif %}
        {% else %}
            <p>未找到对应宾客信息</p>
        {% endif %}
    {% else %}
        <p>该PIN尚未激活</p>
    {% endif %}
{% else %}
    <p>未找到该PIN</p>
{% endif %}

4. 注意事项

  • 确保Pin模型中status字段激活值为'Activated',与视图判断的字符串完全一致
  • 处理所有查询异常,避免页面报错
  • 若Profile与Guest的关联逻辑不是通过用户名,需根据业务调整匹配字段(如手机号)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:20:37