This commit is contained in:
anhduy-tech
2026-01-05 13:40:51 +07:00
parent f43da98b0e
commit 4fd1aae08f
21 changed files with 76 additions and 10 deletions

View File

@@ -209,20 +209,44 @@ class DocumentGenerator:
if not obj:
return None
import re
parts = field_path.split('.')
value = obj
for part in parts:
if value is None:
break
# Lấy thuộc tính từ object
value = getattr(value, part, None)
# 1. Kiểm tra nếu part chứa index mảng, ví dụ: "payment_plan[0]"
array_match = re.match(r"(\w+)\[(\d+)\]", part)
# KIỂM TRA NẾU LÀ QUAN HỆ NGƯỢC (ForeignKey ngược hoặc ManyToMany)
# Trong Django, các quan hệ này trả về một Manager (có method 'all')
if hasattr(value, 'all') and not isinstance(value, models.Model):
value = value.first() # Tự động lấy bản ghi đầu tiên
if array_match:
attr_name = array_match.group(1) # Lấy "payment_plan"
index = int(array_match.group(2)) # Lấy 0
# Lấy list từ object
value = getattr(value, attr_name, None)
# Truy cập phần tử theo index
try:
if isinstance(value, (list, tuple)):
value = value[index]
elif hasattr(value, 'all'): # QuerySet
value = value[index]
except (IndexError, TypeError):
return None
else:
# 2. Xử lý truy cập thuộc tính hoặc key của Dict (JSON)
if isinstance(value, dict):
# Nếu là dict (phần tử trong JSONField), dùng .get()
value = value.get(part)
else:
# Nếu là object, dùng getattr()
value = getattr(value, part, None)
# 3. Hỗ trợ lấy bản ghi đầu tiên nếu gặp Quan hệ ngược (Manager)
if hasattr(value, 'all') and not isinstance(value, models.Model):
value = value.first()
return value
def fetch_data(self):