changes
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from django.db import models
|
||||
|
||||
def resolve_value(expr, context):
|
||||
"""
|
||||
@@ -64,10 +64,36 @@ def resolve_value(expr, context):
|
||||
|
||||
root, *rest = key_path.split(".")
|
||||
val = context.get(root)
|
||||
|
||||
for r in rest:
|
||||
if val is None:
|
||||
return None
|
||||
val = getattr(val, r, None) if not isinstance(val, dict) else val.get(r)
|
||||
|
||||
# 1. Xử lý truy cập index mảng, ví dụ: payment_plan[0]
|
||||
array_match = re.match(r"(\w+)\[(\d+)\]", r)
|
||||
if array_match:
|
||||
attr_name = array_match.group(1)
|
||||
index = int(array_match.group(2))
|
||||
# Lấy list/queryset
|
||||
val = getattr(val, attr_name, None) if not isinstance(val, dict) else val.get(attr_name)
|
||||
try:
|
||||
if hasattr(val, 'all'): # Django QuerySet/Manager
|
||||
val = val[index]
|
||||
else: # List thông thường
|
||||
val = val[index]
|
||||
except (IndexError, TypeError, KeyError):
|
||||
return None
|
||||
else:
|
||||
# 2. Xử lý truy cập thuộc tính hoặc dict key
|
||||
if isinstance(val, dict):
|
||||
val = val.get(r)
|
||||
else:
|
||||
val = getattr(val, r, None)
|
||||
|
||||
# 3. Hỗ trợ tự động lấy bản ghi đầu tiên nếu là Manager (1-n)
|
||||
if hasattr(val, 'all') and not isinstance(val, models.Model):
|
||||
val = val.first()
|
||||
|
||||
return val
|
||||
|
||||
# =============================================
|
||||
|
||||
Reference in New Issue
Block a user