Skip to main content
 首页 » 编程设计

python之Django 查询结果与if语句比较

2025年05月04日35www_RR

需要使用浏览器检查来检查浏览器可更改的值,并将随机 id 输入到按钮中的 url 中,所以我对 django 和东西不是很专业。我对将要更新或删除的数据进行了验证,可以例如,由 tenantid 检查我将在单行记录上按更新,而机制将检查记录 tenantid 是否等于我的租户 id。 问题是我无法将查询结果与 int 值进行比较。

如果有任何更好的方法,我会很高兴听到,谢谢你,祝你今天愉快。

@login_required()  def customer_update(request, pk): 
    customer = get_object_or_404(Customer, pk=pk) 
    valueOwnerTenantid = Customer.objects.values_list('tenantid',   flat=True).filter(id=pk) 
    print(valueOwnerTenantid) 
    print(request.user.tenantid) 
    print(valueOwnerTenantid.query) 
 
    if number(valueOwnerTenantid) == number(request.user.tenantid): 
        if request.method == 'POST': 
            print('Equal and POST') 
            form = CustomerForm(request.POST, instance=customer) 
        else: 
            print('Equal and Get') 
            form = CustomerForm(instance=customer) 
            return save_customer_form(request, form, 'customer_update_partial.html') 
    else: 

请您参考如下方法:

您只对单个值感兴趣,而不是值的 QuerySet,因此您应该使用 .get(..) 而不是 .filter( ) 这里。但实际上您甚至可以完全省略它,因为您已经在 customer 中检索到 tenantid。

因此您的 View 应该如下所示:

@login_required() 
def customer_update(request, pk): 
    customer = get_object_or_404(Customer, pk=pk) 
    if <b>customer.tenantid</b> == request.user.tenantid: 
        # ...

也就是说,您在模型中存储一个 id 而不是某个 Tenant 模型的 ForeignKey 是相当奇怪的,等等。在没有 ForeignKey 的情况下进行引用通常不是一个好主意:tenantid 可能不是例如,指的是真实的租户。此外,默认情况下 Django 不会向 tenantid 列添加索引,这使得搜索具有给定 tenantid 的客户的计算成本更高。