from django.apps import apps from django.db import models STANDARD_OBJECT_REGISTRY = { "Account": ("crm_core", "Account"), "Contact": ("crm_core", "Contact"), "Lead": ("crm_core", "Lead"), "Opportunity": ("crm_core", "Opportunity"), "Activity": ("crm_core", "Activity"), "Campaign": ("outreach", "Campaign"), } EXCLUDED_FIELDS = { "custom_fields", "password", "is_superuser", "is_staff", } DJANGO_TYPE_MAP = { "CharField": "Text", "TextField": "Text Area (Long)", "IntegerField": "Number", "PositiveIntegerField": "Number", "BigAutoField": "AutoNumber", "AutoField": "AutoNumber", "DecimalField": "Currency", "BooleanField": "Checkbox", "DateField": "Date", "DateTimeField": "Date/Time", "ForeignKey": "Lookup", "OneToOneField": "Lookup", "GenericForeignKey": "Generic Lookup", "EmailField": "Email", "URLField": "URL", } def map_field_type(field): if getattr(field, "choices", None): return "Picklist" internal_type = field.get_internal_type() if hasattr(field, "get_internal_type") else type(field).__name__ return DJANGO_TYPE_MAP.get(internal_type, internal_type) def introspect_standard_fields(model_name: str): # Normalize model_name case normalized_name = None for reg_name in STANDARD_OBJECT_REGISTRY: if reg_name.lower() == model_name.lower(): normalized_name = reg_name break if not normalized_name: raise ValueError(f"Unknown standard object: {model_name}") app_label, cls_name = STANDARD_OBJECT_REGISTRY[normalized_name] model = apps.get_model(app_label, cls_name) fields = [] for field in model._meta.get_fields(): # Exclude reverse relations if field.auto_created and not field.concrete: continue if field.name in EXCLUDED_FIELDS: continue data_type = map_field_type(field) choices = [c[0] for c in field.choices] if getattr(field, "choices", None) else [] related_to = None if getattr(field, "is_relation", False) and getattr(field, "related_model", None): related_to = field.related_model.__name__ verbose_name = getattr(field, "verbose_name", field.name) label = str(verbose_name).replace("_", " ").title() if verbose_name else field.name.title() fields.append({ "name": field.name, "label": label, "data_type": data_type, "is_custom": False, "is_required": not getattr(field, "blank", True) and not getattr(field, "null", True), "is_unique": getattr(field, "unique", False), "is_indexed": getattr(field, "db_index", False) or getattr(field, "primary_key", False) or getattr(field, "is_relation", False), "help_text": str(getattr(field, "help_text", "")), "choices": choices, "related_to": related_to, "max_length": getattr(field, "max_length", None), "editable": field.name not in ["id", "created_at", "updated_at"], }) return fields