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

两列数据匹配特定字符串时的Update Query编写及哈希生成问询

How to Write a Django ORM Update Query for Specific ID and Name Values

Hey there! Based on your scenario where you’re generating hashes from id and name fields (plus a secret string) and sending them via email, let’s walk through how to craft the update query you need.

Basic Update Query for Matching ID & Name

If you already have the specific id and name values you want to target, Django’s ORM makes it straightforward to update matching records efficiently. The filter() + update() combo works great for bulk updates (and it doesn’t trigger model save() signals, which is ideal for simple field changes):

# Define your target values (these might come from validating the received hash)
target_id = 456
target_name = "user_satisfaction_survey"

# Update the desired field(s) for records matching both id and name
Query.objects.filter(id=target_id, name=target_name).update(
    status="processed",  # Example field to update
    updated_at=F('updated_at')  # Optional: Use F() to avoid race conditions for timestamp updates
)

Integrating Hash Validation Before Update

Since you’re using hashes to verify the request’s legitimacy, you’ll want to validate the received hash matches the generated hash for the target id and name before making changes. Here’s how to combine that validation with the update logic:

import hashlib
import binascii
from django.db.models import F

# Values from the incoming email/request
received_hash_string = "your_received_hash_here"
target_id = 456  # Could be passed via a link parameter or retrieved from your system

# Your original hash generation parameters (must match what you used to send the hash)
salt = b"satisfaction"
iterations = 100000
secret_string = "yes"

try:
    # Fetch the query record first to validate against
    query_record = Query.objects.get(id=target_id)
    
    # Regenerate the hash to compare with the received one
    data = (str(query_record.id) + str(query_record.name) + secret_string).encode()
    generated_hash = hashlib.pbkdf2_hmac('sha256', data, salt, iterations)
    generated_hash_string = binascii.hexlify(generated_hash).decode()
    
    # Only update if the hash is valid
    if generated_hash_string == received_hash_string:
        # Option 1: Update via object save (triggers model signals like pre_save/post_save)
        query_record.status = "processed"
        query_record.save()
        
        # Option 2: Bulk update (faster, skips signals)
        # Query.objects.filter(id=target_id, name=query_record.name).update(status="processed")
        
        print("Record updated successfully!")
    else:
        print("Invalid hash - update aborted.")
except Query.DoesNotExist:
    print("No matching query record found.")

Key Tips

  • Use filter() instead of get() with update() if you might target multiple records (though your scenario likely uses unique id values).
  • The F() expression avoids race conditions for fields like timestamps or counters by performing the update directly at the database level.
  • If you need to trigger model methods or signals, use the object’s save() method instead of the bulk update() function.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:36:49